Bean XML configuration (4) - Automatic Assembly


Spring series of tutorials


Automated assembly

Introduced in front of use <constructor-arg>and <property>injecting dependencies, we can also use the automatic assembly means to achieve dependency injection, greatly reduce configuration write.

Autowiring locate dependencies in the following ways:

  • byName: by property name. Xml attribute names and class dependent matching bean id.
  • byType: by data type attribute. Property Data Type and dependent matching class bean type, if a plurality of bean can match, a fatal exception is thrown.
  • constructor: data type constructor arguments. Match the data type and constructor parameters depend on the type of bean, if the vessel did not find the type of match Bean, throw a fatal exception.

Automatic assembly Example:

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 configuration:

<bean id="app" class="App" autowire="byType"></bean>

Dependencies array by byType / constructor automatic assembly. Use byType / byName, Java class must implement setter methods.

Use byType / constructor, there may be multiple matching Bean, can be provided by autowire-candidate="false"removing the matching.
Example:

<bean id="app" class="App" autowire="byType"></bean>
<bean id="database" class="Database" autowire-candidate="false"></bean>
<bean id="mail" class="Mail" autowire-candidate="false"></bean>
<bean id="logger" class="Logger" autowire-candidate="true"></bean>

Use byName, automatically assembled as follows mainService, App class attributes mainServiceand <bean id="mainService"match:

<bean id="app" class="App" autowire="byName"></bean>
<bean id="database" class="Database"></bean>
<bean id="mail" class="Mail"></bean>
<bean id="mainService" class="Logger"></bean>

Limitations of Automatic Assembly

  • The possibility of being covered : by still <constructor-arg>and <property>configuration override automatic assembly configuration.
  • Primitive data types not supported : mode values of the original data type can not be automatically assembled injection.
  • It is not precise enough : manual assembly precision is better to automatic assembly, to make use of manual assembly.

Guess you like

Origin www.cnblogs.com/jinbuqi/p/10971684.html