10.autowired自动装配
Dept类
package Spring5.autowire;
public class Dept
{
@Override
public String toString() {
return "Dept{}";
}
}
Emp1类
package Spring5.autowire;
public class Emp1 {
private Dept dept;
public void setDept(Dept dept) {
this.dept = dept;
}
public void show(){
System.out.println(dept);
}
}
bean9.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">
<!-- 手动装配
<bean id="Emp1" class="Spring5.autowire.Emp1" >
<property name="dept" ref="Dept"></property>
</bean>
<bean id="Dept" class="Spring5.autowire.Dept"></bean>
-->
<!--自动装配 id要与类中的属性名称一致
<bean id="Emp1" class="Spring5.autowire.Emp1" autowire="byName"></bean>
<bean id="dept" class="Spring5.autowire.Dept"></bean>
-->
<!--自动装配byType-->
<bean id="Emp1" class="Spring5.autowire.Emp1" autowire="byType"></bean>
<bean id="Dept" class="Spring5.autowire.Dept"></bean>
</beans>
Test类
public class TEST {
@Test
public void testBean9(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean9.xml");
Emp1 emp = context.getBean("Emp1", Emp1.class);
emp.show();
}
}