这篇文章主要讲解了“spring IOC容器的Bean管理XML自动装配怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“spring IOC容器的Bean管理XML自动装配怎么实现”吧!
在之前的内容中,每给属性注入值都要一个个的用 property 标签来完成,比如:
<bean id="book" class="com.pingguo.spring5.collectiontype.Book" scope="prototype">
<property name="list" ref="bookList"></property>
</bean>
这就是手动装配。
而自动装配中,spring 会根据指定装配规则(属性名称或者属性类型) 来自动的将匹配的属性值进行注入。
分别是部门类 Department 和员工类 Employee 。
package com.pingguo.spring5.autowire;
public class Department {
@Override
public String toString() {
return "Department{}";
}
}
员工类有个 部门的属性,表示员工所属的一个部门。其他方法是为了后续方便演示输出。
package com.pingguo.spring5.autowire;
public class Employee {
private Department department;
public void setDepartment(Department department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" +
"department=" + department +
'}';
}
public void test() {
System.out.println(department);
}
}
<?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="employee" class="com.pingguo.spring5.autowire.Employee">
<property name="department" ref="department"></property>
</bean>
<bean id="department" class="com.pingguo.spring5.autowire.Department"></bean>
</beans>
@Test
public void test5() {
ApplicationContext context =
new ClassPathXmlApplicationContext("bean5.xml");
Employee employee = context.getBean("employee", Employee.class);
System.out.println(employee);
}
运行结果:
Employee{department=Department{}}
Process finished with exit code 0
ok,到这里,其实就是手动装配的过程。
实现自动装配,在配置文件里,通过 bean 标签里的属性 autowire 来配置:
autowire="byName":根据属性名称自动注入。
autowire="byType":根据属性类型自动注入。
1)byName 演示
注入值的bean的 id 值和类属性名称一致,比如:
修改配置文件,加上 autowire="byName",然后注释掉 property。
<bean id="employee" class="com.pingguo.spring5.autowire.Employee" autowire="byName">
<!--<property name="department" ref="department"></property>-->
</bean>
<bean id="department" class="com.pingguo.spring5.autowire.Department"></bean>
执行测试函数:
Employee{department=Department{}}
Process finished with exit code 0
跟使用 property 手动装配结果一致。
2)byType 演示
要注入值的 bean 的类型与 属性里的一致,比如:
现在继续修改配置文件,加上 autowire="byType",然后注释掉 property。
<bean id="employee" class="com.pingguo.spring5.autowire.Employee" autowire="byType">
<!--<property name="department" ref="department"></property>-->
</bean>
<bean id="department" class="com.pingguo.spring5.autowire.Department"></bean>
再次执行测试:
Employee{department=Department{}}
Process finished with exit code 0
跟使用 property 手动装配结果一致。
感谢各位的阅读,以上就是“spring IOC容器的Bean管理XML自动装配怎么实现”的内容了,经过本文的学习后,相信大家对spring IOC容器的Bean管理XML自动装配怎么实现这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。