像之前的
<bean id="myStudent" class="org.chentianyu.ba02.Student"><property name="name" value="李四" /><property name="age" value="22" /><!--引用类型--><property name="school" ref="mySchool" /></bean>
你必须手动赋值,你不赋值他就没有,但是在我们项目开发中,这种引用类型在一个类中会有很多,如果这样去赋值会有大量的冗余语句。
bean02>applicationContext.xml
<?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">
<!--
引用类型自动注入: spring框架根据某些规矩可以给引用类型赋值(只能对引用类型有效)
使用的规则常用的是byName,byType.
byName: 按名称注入: java类中引用类型的属性名,和spring容器中(配置文件)<bean>的id名称一样,且数据是一致的,这样的容器中的bean,spring能够赋值给引用类型
-->
<bean id="myStudent" class="org.chentianyu.ba02.Student" autowire="byName">
<property name="name" value="李四" />
<property name="id" value="1" />
<property name="age" value="20" />
<!-- <property name="school" ref="mySchool" />-->
</bean>
<bean id="mySchool" class="org.chentianyu.ba02.School">
<property name="name" value="杭州职业技术学院" />
<property name="address" value="杭州下沙" />
</bean>
</beans>
@Test
public void testZdByName01(){
String config = "bean02/applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(config);
Student myStudent = (Student) applicationContext.getBean("myStudent");
System.out.println(myStudent);
}
无参构造方法执行了
Student{id=1, name='李四', age=20, school=null}
如果将school的id改成Student类里面的形参变量名:
<?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">
<!--
引用类型自动注入: spring框架根据某些规矩可以给引用类型赋值(只能对引用类型有效)
使用的规则常用的是byName,byType.
byName: 按名称注入: java类中引用类型的属性名,和spring容器中(配置文件)<bean>的id名称一样,且数据是一致的,这样的容器中的bean,spring能够赋值给引用类型
-->
<bean id="myStudent" class="org.chentianyu.ba02.Student" autowire="byName">
<property name="name" value="李四" />
<property name="id" value="1" />
<property name="age" value="20" />
<!-- <property name="school" ref="mySchool" />-->
</bean>
<bean id="school" class="org.chentianyu.ba02.School">
<property name="name" value="杭州职业技术学院" />
<property name="address" value="杭州下沙" />
</bean>
</beans>
无参构造方法执行了
Student{id=1, name='李四', age=20, school=School{name='杭州职业技术学院', address='杭州下沙'}}
