自动装配
- 自动装配就是指我们无需手动取注入类里边的属性,bean会通过
autowire
帮助我们自动取注入属性 autowire
内有两个值,一个是byName
,另一个是byType
byName
是通过名称自动装配,byType
是通过类型自动装配- 除非特殊情况,否则不建议使用
byType
,byType
当需要注入的类型重复时会报错
一、 通过byName
实现自动装配
首先创建Stu类和Class_stu类
package com.atguigu.spring5.xmlbeanzdzp;
public class Stu {
@Override
public String toString() {
return "Stu{}";
}
}
package com.atguigu.spring5.xmlbeanzdzp;
public class Class_stu {
private Stu stu;
public void setStu(Stu stu) {
this.stu = stu;
}
@Override
public String toString() {
return "Class_stu{" +
"stu=" + stu +
'}';
}
}
配置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 name="class_stu" class="com.atguigu.spring5.xmlbeanzdzp.Class_stu" autowire="byName"></bean>
<bean name="stu" class="com.atguigu.spring5.xmlbeanzdzp.Stu"></bean>
</beans>
创建测试类
public class TestSpring5 {
@Test
public void testzdzp(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean6.xml");
Class_stu cls=context.getBean("class_stu",Class_stu.class);
System.out.println(cls);
}
}
运行测试类结果如下
至此我们完成了通过名称的自动装配
二、通过byType
实现自动装配
改动上述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 name="class_stu" class="com.atguigu.spring5.xmlbeanzdzp.Class_stu" autowire="byType"></bean>
<bean name="stu" class="com.atguigu.spring5.xmlbeanzdzp.Stu"></bean>
</beans>