spring@autowired Annotations and automatic assembly (forwarding)

Source: Internet
Author: User


1 Ways to configure files

When we write the code for the Spring framework. Always follow a rule: All beans injected in spring are recommended to be defined as private domain variables. Also write the Get and set methods.

Bosses have two properties for Office and Car types:
Listing 3. Boss.java

 package   Com.baobaotao;  public  class  Span style= "Color:rgb (0, 0, 0);         > Boss { private   car car;              private   office office;  //  omit Get/setter  @Override   String toString () { return  "car:" + car + "/n" + "office:         "+ office; }     }

System.out.println must implement the ToString method
We declare Office and Car as beans in the Spring container and inject it into the Boss bean: The following is the configuration file Beans.xml, which accomplishes this work using traditional XML:
Listing 4. Beans.xml Configure the above three classes as beans

<?XML version= "1.0" encoding= "UTF-8"?>     <Beansxmlns= "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 ">         <BeanID= "Boss"class= "Com.baobaotao.Boss">             < Propertyname= "Car"ref= "Car"/>             < Propertyname= "Office"ref= "Office" />         </Bean>         <BeanID= "Office"class= "Com.baobaotao.Office">             < Propertyname= "Officeno"value= "002"/>         </Bean>         <BeanID= "Car"class= "Com.baobaotao.Car"Scope= "Singleton">             < Propertyname= "Brand"value= "Red Flag CA72"/>             < Propertyname= "Price"value= "$"/>         </Bean>     </Beans>

When we run the following code, the console will correctly punch the boss's message:
Listing 5. Test class: Annoioctest.java

ImportOrg.springframework.context.ApplicationContext; ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;  Public classAnnoioctest { Public Static voidMain (string[] args) {string[] locations= {"Beans.xml"}; ApplicationContext CTX=NewClasspathxmlapplicationcontext (locations); Boss Boss= (boss) Ctx.getbean ("Boss"));         SYSTEM.OUT.PRINTLN (boss); }     }

This means that the Spring container has correctly completed the work of Bean creation and assembly.

2 @Autowired

Spring 2.5 introduces @Autowired annotations that allow you to annotate class member variables, methods, and constructors, and complete the task of automating Assembly. Use the @Autowired to eliminate the set, get method.

To achieve the purpose of streamlining our procedures. This is required to handle:
* Add in Applicationcontext.xml:

<!---       <class = " Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>

Spring parses @Autowired with a beanpostprocessor, so @Autowired must be declared in the Spring container beforehand Autowiredannotationbeanpostprocessor Bean.

* Modify the method of the bean in the original injected SPIRNG container.
Add label @autowired to the domain variable and remove the corresponding get and set methods

Listing 6. Using the Boss.java of @Autowired annotations

 Package Com.baobaotao;      Import org.springframework.beans.factory.annotation.Autowired;           Public class Boss {             @Autowired        private  car car;             @Autowired        Private  Office office;             ...     }

* Remove the original quoted <porpery > tags from the applicatoncontext.xml.

<?XML version= "1.0" encoding= "UTF-8"?>     <Beansxmlns= "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 ">             <!--the Beanpostprocessor will automatically function to automatically inject the Bean labeled @Autowired -         <Beanclass= "Org.springframework.beans.factory.annotation." Autowiredannotationbeanpostprocessor "/>             <!--Remove the attribute injection configuration information for the boss Bean -         <BeanID= "Boss"class= "Com.baobaotao.Boss"/>               <BeanID= "Office"class= "Com.baobaotao.Office">             < Propertyname= "Officeno"value= "001"/>         </Bean>         <BeanID= "Car"class= "Com.baobaotao.Car"Scope= "Singleton">             < Propertyname= "Brand"value= "Red Flag CA72"/>             < Propertyname= "Price"value= "$"/>         </Bean>     </Beans>

This way, when the spring container starts, Autowiredannotationbeanpostprocessor will scan all the beans in the spring container, and when it finds that the bean has @Autowired Note, the Bean that matches it (the default by type) is found and injected into the corresponding place.
According to the above configuration, Spring will directly use the Java reflection mechanism to automatically inject the private member variables of car and office in the Boss. So when you use @Autowired for member variables, you can delete their setter methods (Setcar () and Setoffice ()) from the Boss.
Of course, you can also annotate a method or constructor by @Autowired, if the constructor has two entry parameters, Bean1 and bean2, respectively, @Autowired will look for the beans that match their type, and use them as Countryservice ( Bean1 bean1, Bean2 bean2) to create the Countryservice Bean. Look at the following code: on the method

 PackageCom.baobaotao;  Public classBoss {Privatecar Car; PrivateOffice Office; @Autowired Public voidSetcar (car car) { This. Car =car; } @Autowired Public voidsetoffice (Office office) { This. Office =Office; } ...}

At this point, @Autowired will look for the bean of the input type of the method being labeled and invoke the method to inject the beans automatically. The constructor is annotated with the following usage method:

 PackageCom.baobaotao;  Public classBoss {Privatecar Car; PrivateOffice Office; @Autowired Public voidSetcar (car car) { This. Car =car; } @Autowired Public voidsetoffice (Office office) { This. Office =Office; } ...


Because the boss () constructor has two entry parameters, car and office, @Autowired will look for beans that match their type, creating a boss bean as part of the boss (car car, office Office).


Transferred from: http://blog.csdn.net/heyutao007/article/details/5981555

[email protected] annotations and automatic assembly (forwarding)

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.