简单类型属性的赋值(set注入)
set注入要求
JavaBean必须要有set方法,因为ioc容器是使用javabean的set方法进行属性赋值的
spring容器调用的是setXxx()方法,而不管对象是否具有Xxx属性(即对象没有的属性只要有set方法也可以实现注入),Xxx不区分大小写
JavaBean
public class Student {
private String name;
private int age;
private School school;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSchool(School school) {
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
", school=" + school +
'}';
}
}
spring配置文件
<!--声明Student对象-->
<bean id="student" class="com.mms.component.Student">
<!--
1、简单类型使用property和value标签给对象属性赋值
2、简单类型:8个基本类型+String
3、当spring容器加载到这一行时会在创建完对象的同时使用对象的set方法给属性赋值,底层
调用的是对象的set方法
4、spring容器调用的是setXxx()方法,而不管对象是否具有Xxx属性,Xxx不区分大小写
-->
<property name="name" value="张三"/>
<property name="age" value="23"/>
<!--测试对象没有属性的set方法-->
<property name="graName" value="s1"/>
</bean>
测试类
//使用set注入给对象属性赋值
@Test
public void test01() {
String config = "ba01/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//执行完14行此时Student对象的属性已被赋值,获取对象进行验证
Student stu = (Student) ac.getBean("student");
System.out.println(stu); //Student{name='张三', age=23}
}
//验证set注入调用的是对象的set方法
@Test
public void test02() {
String config = "ba01/applicationContext.xml";
/*
* 此时会调用set方法进行赋值
* setName...
* setAge...
*/
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
}
//验证没有属性的setXxx方法是否报错
@Test
public void test03() {
String config = "ba01/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(config);
//获取对象
Student stu = (Student) ac.getBean("student");
}