Spring Learning (vi)-----Spring Automatic assembly using @autowired annotations

Source: Internet
Author: User

Spring uses @autowired annotations to automatically assemble in the previous articleSpring Learning (iii)-----Spring automatic assembly Beansexample, it will match the properties of any bean in the current spring container automatically assembled. In most cases, you may only need to automatically assemble properties in a particular bean. In spring, you can use @Autowired annotations to automatically assemble beans through setter methods, constructors, or fields. In addition, it can be automatically assembled in a specific bean attribute. Note@Autowired annotations are automatic assembly of beans by matching data types. See the complete example below to demonstrate how to use @autowired. 1. Beans a Customer Bean is declared in the bean configuration file. Later, you will use "@Autowired" to automatically assemble a person bean.
 PackageCom.yiibai.common; Public classCustomer {//You want autowired this field.    Privateperson person ; Private inttype; PrivateString Action; //getter and setter method    }<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-2.5.xsd "><bean id= "Customerbean"class= "Com.yiibai.common.Customer" > <property name= "Action" value= "buy"/> <property name= "type" Valu e= "1"/> </bean> <bean id= "Personbean"class= "Com.yiibai.common.Person" > <property name= "name" value= "Yiibai"/> <property name= "Address" va Lue= "Address 123"/> <property name= "age" value= ""/> </bean> </beans>

2. Register autowiredannotationbeanpostprocessor to enable @autowired, you must register "Autowiredannotationbeanpostprocessor", You can do this in one of two ways: 1. Include <context:annotation-config/> Add  Spring  context and <context:annotation-config /> In the bean configuration file.
<beans     //...    xmlns:context= "Http://www.springframework.org/schema/context"    //...    http://www.springframework.org/schema/context    http://  Www.springframework.org/schema/context/spring-context-2.5.xsd ">    //...    <context:annotation-config/>    //... </beans>

The following is a complete example

<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-2.5.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-2.5.xsd "><context:annotation-config/> <bean id= "Customerbean"class= "Com.yiibai.common.Customer" > <property name= "Action" value= "buy"/> <property name= "type" Valu e= "1"/> </bean> <bean id= "Personbean"class= "Com.yiibai.common.Person" > <property name= "name" value= "Yiibai"/> <property name= "Address" va Lue= "Address ABC"/> <property name= "age" value= "/> </bean> </beans>"

2. Contains autowiredannotationbeanpostprocessor directly in the bean configuration file that contains "Autowiredannotationbeanpostprocessor".
<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-2.5.xsd "><Beanclass= "Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id= " Customerbean "class= "Com.yiibai.common.Customer" > <property name= "Action" value= "buy"/> <property name= "type" Valu e= "1"/> </bean> <bean id= "Personbean"class= "Com.yiibai.common.Person" > <property name= "name" value= "Yiibai"/> <property name= "Address" va Lue= "Address ABC"/> <property name= "age" value= "/> </bean> </beans>"

3. @Autowired example Now you can automate the assembly of beans by @Autowired, which can be used in setter methods, constructors, or fields. 1. @Autowired Setter Method
 PackageCom.yiibai.common;Importorg.springframework.beans.factory.annotation.Autowired; Public classCustomer {Privateperson person ; Private inttype; PrivateString Action; //getter and Setter methods@Autowired Public voidSetperson (person person) { This. person =Person ; }}

2. @Autowired Construction method
 PackageCom.yiibai.common;Importorg.springframework.beans.factory.annotation.Autowired; Public classCustomer {Privateperson person ; Private inttype; PrivateString Action; //getter and Setter methods@Autowired PublicCustomer (person person) { This. person =Person ; }}

3. @Autowired Field
 Package Com.yiibai.common; Import org.springframework.beans.factory.annotation.Autowired;  Public class Customer {    @Autowired    private person person ;     Private int type;     Private String action;     // getter and Setter Methods}

The example above automatically assembles "Personbean" to the customer's Person property.

Execute it

 PackageCom.yiibai.common;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classApp { Public Static voidMain (string[] args) {ApplicationContext context=NewClasspathxmlapplicationcontext (NewString[] {"Applicationcontext.xml"}); Customer Cust= (Customer) context.getbean ("Customerbean");            SYSTEM.OUT.PRINTLN (Cust); }}

Output

Customer [Person=person [Name=yiibaia], type=1, Action=buy]
Dependency checking

By default, @Autowired checks are performed to ensure that the properties are properly assembled. When spring cannot find a matching bean assembly, it throws an exception. To resolve this problem, you can disable this check by setting the Required property to False @Autowired.

 Package Com.yiibai.common; Import org.springframework.beans.factory.annotation.Autowired;  Public class Customer {    @Autowired (required=false)    private person person ;     privateint  type;     Private String action;     // getter and Setter Methods}

In the example above, if spring cannot find a matching Bean,person property, it will not be set. @Qualifier @qualifier Annotations We use to control that the bean should be automatically assembled on the field. For example, it has two similar person bean profiles.
<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-2.5.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context-2.5.xsd "><context:annotation-config/> <bean id= "Customerbean"class= "Com.yiibai.common.Customer" > <property name= "Action" value= "buy"/> <property name= "type" Valu e= "1"/> </bean> <bean id= "PersonBean1"class= "Com.yiibai.common.Person" > <property name= "name" value= "yiibai-1"/> <property name= "Address" Value= "Address-1"/> <property name= "age" value= ""/> </bean> <bean id= "PersonBean2"class= "Com.yiibai.common.Person" > <property name= "name" value= "Yiibai-2"/> <property name= "Address" Value= "Address-2"/> <property name= "age" value= "Up"/> </bean> </beans>

Does spring know which bean should be assembled? To solve this problem, you can use @Qualifier to automatically assemble a particular bean, for example,
 PackageCom.yiibai.common;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.beans.factory.annotation.Qualifier; Public classCustomer {@Autowired @Qualifier ("PersonBean1")    Privateperson person ; Private inttype; PrivateString Action; //getter and Setter methods}

This means that the "PersonBean1" Bean is automatically assembled to the customer's Person property.

Summarizing this @autowired annotation is very flexible and powerful, and is definitely better than the "Autowire" attribute of the bean profile.

Spring Learning (vi)-----Spring Automatic assembly using @autowired annotations

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.