Spring-01 实现简单的Spring程序

spring中的控制反转IOC主要是将对象的创建交给spring容器来做,而不需要在程序中主动通过new的方式来造出对象。
spring的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--bean就当做是java对象 , 由Spring创建和管理。id属性可以当做class这个类的名字,
    在程序中通过id属性来获取到对应的类。property属性用来设置这个类的属性的初始值-->
    <bean id="h1" class="xyz.bryce.pojo.hello1">
        <property name="str" value="hello world"/>
    </bean>

</beans>

每当写一个类,就将其写入到上面的spring的配置文件中,就这相当于将这个类交给spring容器进行管理了。
当程序需要用到这个类时,就由spring容器给出这个类的实例。类中的属性 一定要有set方法,在bean中,类的属性的赋值是根据set方法来设置的。如果没有set方法,在 property 标签写上该属性时就会显示错误。

package xyz.bryce.pojo;
public class hello1 {
    private String str;
    public void setStr(String str) {
        this.str = str;
    }
    @Override
    public String toString() {
        return "hello1{" +
                "str='" + str + '\'' +
                '}';
    }
}

获取类时:

    @Test
    public void test1(){
        ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
        hello1 h1 = (hello1) context1.getBean("h1");
        System.out.println(h1);
    }

beans.xml时spring的配置文件,ClassPathXmlApplicationContext用来从类路径加载配置文件,得到的ApplicationContext
允许spring通过应用程序上下文来创建、获取、管理bean。通过方法getBean就可以得到对应的类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值