Spring bean dependency injection, bean assembly and related annotations, springbean

Source: Internet
Author: User

Spring bean dependency injection, bean assembly and related annotations, springbean
Dependency Injection

Spring provides the following two methods for dependency injection:

  • Property-based Setter method Injection
  • Constructor Injection
Setter method Injection

Example:

public class Communication {     private Messaging messaging;           /*     * DI via Setter     */    public void setMessaging(Messaging messaging){        this.messaging = messaging;    }     public void communicate(){        messaging.sendMessage();    }}

The above Communication class has a messaging attribute and contains the setMessaging method. When using the Setter Method for injection, you only need to use the following XML Configuration:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <bean id="activeMqMessaging" class="com.websystique.spring.domain.impl.ActiveMQMessaging" />     <bean id="communication" class="com.websystique.spring.Communication">        <property name="messaging">            <ref bean="activeMqMessaging" />        </property>    </bean> </beans>

The definition of ActiveMQMessaging is omitted here. In fact, the ActiveMQMessaging class isMessagingAn Implementation class of the interface.

Constructor Injection

Example

public class Communication {     private Encryption encryption;         /*     * DI via Constructor Injection     */    public Communication(Encryption encryption){        this.encryption = encryption;    }      public void communicate(){        encryption.encryptData();    } }

Note that the preceding Communication class has a constructor: Communication (Encryption encryption), which contains an input parameter and the type is Encryption. The XML configuration for Constructor injection is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <bean id="rsaEncryption" class="com.websystique.spring.domain.impl.RSAEncryption" />     <bean id="communication" class="com.websystique.spring.Communication">        <constructor-arg type="com.websystique.spring.domain.Encryption">            <ref bean="rsaEncryption" />        </constructor-arg>    </bean> </beans>

Note: The RSAEncryption definition is omitted here, so you don't need to care about these details. This class isEncryptionAn Implementation class of the interface.

In addition, to avoid ambiguity caused by overload of constructor methods, the input parameter type is com. webjavasique. spring. domain. Encryption.

Assembly

Bean can be assembled manually or automatically. Note: Do not confuse. bean Assembly depends on the specific behavior of injection. When dependency injection is performed, it must be assembled according to the bean name or type.

Manual assembly: By using the ref attribute in the <property> or <constructor> label, manual assembly is used in the "dependency injection" section of the previous section;

<!-- default example (autowire="no") --><bean id="driver" class="com.websystique.spring.domain.Driver">    <property name="license" ref="license"/></bean> <bean id="license" class="com.websystique.spring.domain.License" >    <property name="number" value="123456ABCD"/></bean>

Automatic Assembly: Used in the <bean> labelautowireAttribute;

<bean id="application" class="com.websystique.spring.domain.Application" autowire="byName"/>

This section focuses on automatic assembly. There are four methods for automatic assembly:

  • autowire="byName": By name
  • autowire="byType": Based on Type
  • autowire="constructor": Input parameter type based on the constructor
  • autowire="no": Automatic assembly is not used, that is, the default mode is manual assembly.
autowire="byName"

Example:

public class Application {     private ApplicationUser applicationUser;     public ApplicationUser getApplicationUser() {        return applicationUser;    }     public void setApplicationUser(ApplicationUser applicationUser) {        this.applicationUser = applicationUser;    }     @Override    public String toString() {        return "Application [applicationUser=" + applicationUser + "]";    }}

This class has an attribute calledapplicationUserThe XML configuration automatically assembled by name is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <!-- byName example -->    <bean id="application" class="com.websystique.spring.domain.Application" autowire="byName"/>     <bean id="applicationUser" class="com.websystique.spring.domain.ApplicationUser" >        <property name="name" value="superUser"/>    </bean>
</beans>
autowire="byType"

Example

public class Employee {     private EmployeeAddress address;     public EmployeeAddress getAddress() {        return address;    }     public void setAddress(EmployeeAddress address) {        this.address = address;    }     @Override    public String toString() {        return "Employee [address=" + address + "]";    }}

This class has an attribute typeEmployeeAddress, The XML configuration automatically assembled Based on the type is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <!-- byType example -->    <bean id="employee" class="com.websystique.spring.domain.Employee" autowire="byType"/>     <bean id="employeeAddress" class="com.websystique.spring.domain.EmployeeAddress" >        <property name="street" value="112/223,SantaVila"/>        <property name="city" value="Nebraska"/>    </bean> </beans>
autowire="constructor"

Example

public class Performer {         private Instrument instrument;         public Performer(Instrument instrument){        this.instrument = instrument;    }     @Override    public String toString() {        return "Performer [instrument=" + instrument + "]";    }}

This class has a constructor. The input parameter type is Instrument.The XML configuration automatically assembled according to the construction method is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <!-- constructor example -->    <bean id="performer" class="com.websystique.spring.domain.Performer" autowire="constructor"/>     <bean id="instrument" class="com.websystique.spring.domain.Instrument" >        <property name="name" value="PIANO"/>    </bean> </beans>
autowire="no"
public class Driver {     private License license;         public void setLicense(License license) {        this.license = license;    }     public License getLicense() {        return license;    }     @Override    public String toString() {        return "Driver [license=" + license + "]";    }}

This class has a property license. Because we do not intend to use the automatic assembly function, we can only use manual assembly. The XML configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">     <!-- default example (autowire="no") -->    <bean id="driver" class="com.websystique.spring.domain.Driver" autowire="no">        <property name="license" ref="license"/>    </bean>     <bean id="license" class="com.websystique.spring.domain.License" >        <property name="number" value="123456ABCD"/>    </bean> </beans>

Note: If the ref reference of the license is not configured, the license is null.

Related annotations

It mainly involves the following three Annotations:

  • @Autowired
  • @Resource
  • @Qualifier

@ Autowired can be applied to the constructor, attribute, setter method, or Configuration class @ Configuration method. This annotation is assembled Based on the bean data type, if you want to assemble bean names, you can use@ResourceAnnotation; in addition@QualifierAnnotations are often used in combination with the @ Autowired annotation to solve the problem of multiple beans of the same type in an application. The following is an example of each annotation.

@Autowired(Automatic Assembly based on type)

Setter Method

@Component("driver")public class Driver {     private License license;         @Autowired    public void setLicense(License license) {        this.license = license;    }     @Override    public String toString() {        return "Driver [license=" + license + "]";    }    //getter}

Constructor

@Component("driver")public class Driver {     private License license;         @Autowired    public Driver(License license){        this.license = license;    }         @Override    public String toString() {        return "Driver [license=" + license + "]";    }}

Attribute

@Component("driver")public class Driver {    @Autowired    private License license;         //getter,setter     @Override    public String toString() {        return "Driver [license=" + license + "]";    }}
@Resource(Name-based assembly)
@Component("application")public class Application {     @Resource(name="applicationUser")    private ApplicationUser user;     @Override    public String toString() {        return "Application [user=" + user + "]";    }}
@Qualifier( @AutowiredCombined use to achieve name-based assembly)

Example Background: There are two Car interface implementation classes. The implementation class of one Car interface has been registered as bean and the name is Mustang.

@Componentpublic class Bond {     @Autowired    @Qualifier("Mustang")    private Car car;         public void showCar(){        car.getCarName();    }}

Note: If the preceding example is not used@QualifierIf this parameter is specified, the following exception is thrown, indicating that multiple beans of the same type exist:

Caused by: org. springframework. beans. factory. noUniqueBeanDefinitionException: No qualifying bean of type [com. webpolicique. spring. domain. car] is defined: expected single matching bean but found 2: Ferari, Mustang
At org. springframework. beans. factory. support. DefaultListableBeanFactory. doResolveDependency (DefaultListableBeanFactory. java: 970)
At org. springframework. beans. factory. support. DefaultListableBeanFactory. resolveDependency (DefaultListableBeanFactory. java: 858)
At org. springframework. beans. factory. annotation. AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement. inject (AutowiredAnnotationBeanPostProcessor. java: 480)
... 14 more

Finally, the @ Autowired annotation ensures successful injection by default. If the injection fails (usually cannot be found or is ambiguous), Spring will throw an exception. Of course, sometimes there may be special requirements. If you do not want beans to be forcibly assembled, you can add them on @ Autowired.required=falseAttribute, indicating that the bean assembly is optional. If it cannot be found, it is null, as shown in the following example:

@Component("driver")public class Driver {    @Autowired(required=false)    private License license;         //getter,setter     @Override    public String toString() {        return "Driver [license=" + license + "]";    }}

For the above reasons, although the @ Autowired annotation is similar to the @ Resource function, @ Autowired is a little more powerful than @ Resource. I suggest using the @ Autowired annotation.

References

Http://websystique.com/spring/spring-dependency-injection-example-with-constructor-and-property-setter-xml-example/

Http://websystique.com/spring/spring-beans-auto-wiring-example-using-xml-configuration/

Http://websystique.com/spring/spring-dependency-injection-annotation-beans-auto-wiring-using-autowired-qualifier-resource-annotations-configuration/

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.