Bean XML 配置(4)- 自动装配


Spring 系列教程


自动装配

前面介绍了使用<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>配置覆盖自动装配的配置。
  • 不支持原始数据类型: 原始数据类型的值不能通过自动装配的方式注入。
  • 不够精准: 自动装配不如手动装配精准,尽量使用手动装配。