本文主要介绍基于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"<