【Spring】-基于XML管理bean

本文主要介绍基于xml文件配置,如何对bean中不同类型属性配置取值

1、setter注入

xml定义:

<bean id="student" class="com.lucky.spring.pojo.Student">
        <property name="sid" value="0001"></property>
        <property name="sname" value="lisa"></property>
        <property name="age" value="22"></property>
        <property name="gender" value="n"></property>
</bean>

双加property标签,可以看到,property标签是通过settter方法来给bean属性赋值的
在这里插入图片描述测试类:

  @Test
    public void test01() {
   
        ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = appContext.getBean(Student.class);
        System.out.println(student);
    }

代码输出为:
在这里插入图片描述此时各个属性取值已注入。
总结:
property标签:通过组件类的setXxx()方法给组件对象设置属性
name属性:指定属性名(这个属性名是getXxx()、setXxx()方法定义的,和成员变量无关)
value属性:指定属性值

2、构造函数注入

可以利用constructor-arg标签,利用构造函数,为bean属性注入值。
xml文件:

  <bean id="student1" class="com.lucky.spring.pojo.Student">
        <constructor-arg value="0002"></constructor-arg>
        <constructor-arg value="lisa2"></constructor-arg>
        <constructor-arg value="23"></constructor-arg>
        <constructor-arg value="n"></constructor-arg>
    </bean>

注意:必须保证bean里面有对应的构造函数定义。
测试:

 @Test
    public void test01() {
   
        ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = appContext.getBean("student1", Student.class);
        System.out.println(student);
    }

constructor-arg标签还有两个属性可以进一步描述构造器参数:
index属性:指定参数所在位置的索引(从0开始)
name属性:指定参数名

3、特殊值注入

a、基本类型,string,包装类型,直接利用value属性即可

<property name="sid" value="0001"></property>

b、null值

  <!--给name赋值为null-->
    <bean id="student2" class="com.lucky.spring.pojo.Student">
        <property name="sid"<
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值