Bean XML 配置(4)- 自动装配
Spring 系列教程
- Spring 框架介绍
- Spring 框架模块
- Spring开发环境搭建(Eclipse)
- 创建一个简单的Spring应用
- Spring 控制反转容器(Inversion of Control – IOC)
- 理解依赖注入(DI – Dependency Injection)
- Bean XML 配置(1)- 通过XML配置加载Bean
- Bean XML 配置(2)- Bean作用域与生命周期回调方法配置
- Bean XML 配置(3)- 依赖注入配置
- Bean XML 配置(4)- 自动装配
- Bean 注解(Annotation)配置(1)- 通过注解加载Bean
- Bean 注解(Annotation)配置(2)- Bean作用域与生命周期回调方法配置
- Bean 注解(Annotation)配置(3)- 依赖注入配置
- Bean Java配置
- Spring 面向切面编程(AOP)
- Spring 事件(1)- 内置事件
- Spring 事件(2)- 自定义事件
自动装配
前面介绍了使用<constructor-arg>
和<property>
注入依赖项,我们还可以使用自动装配的方式实现依赖注入,大大减少配置编写。
自动装配通过以下方式查找依赖项:
- byName: 通过属性名。匹配类中的属性名和xml中依赖bean id。
- byType: 通过属性数据类型。匹配类中的属性数据类型和依赖bean类型,如果可以匹配多个bean,则抛出致命异常。
- constructor: 通过构造函数参数的数据类型。匹配构造函数参数的数据类型和依赖bean类型,如果容器中没找到类型匹配的Bean,抛出致命异常。
自动装配示例:
public class App {
private Service mainService;
private Service[] services;
// 注入Service实例
public App(Service main){
this.mainService = main;
}
// 注入Service实例数组
public App(Service[] services){
this.services = services;
}
public Service getMainService() {
return mainService;
}
// 通过setter方法注入服务实例
public void setMainService(Service mainService) {
this.mainService = mainService;
}
public Service[] getServices() {
return services;
}
// 通过setter方法注入服务实例数组
public void setServices(Service[] services) {
this.services = services;
}
}
xml配置:
<bean ></bean>
依赖项数组可通过byType/constructor自动装配。使用byType/byName,Java类必须实现setter方法。
使用byType/constructor,可能有多个Bean匹配,可通过设置autowire-candidate="false"
去除匹配。
示例:
<bean ></bean>
<bean ></bean>
<bean ></bean>
<bean ></bean>
使用byName,如下所示会自动装配mainService,App类中的属性mainService
与<bean
匹配:
<bean ></bean>
<bean ></bean>
<bean ></bean>
<bean ></bean>
自动装配的局限性
-
被覆盖的可能性: 仍可通过
<constructor-arg>
和<property>
配置覆盖自动装配的配置。 - 不支持原始数据类型: 原始数据类型的值不能通过自动装配的方式注入。
- 不够精准: 自动装配不如手动装配精准,尽量使用手动装配。