Spring Annotated source code Analysis--how does autowired works?

Source: Internet
Author: User

1. Background

Annotations can reduce the amount of code development, and spring provides rich annotation capabilities. We may be asked, what is the triggering of spring's annotations? Today, we use one of spring's most frequently used annotation autowired to track code and debug.

2. Definition and role of autowired

Functions: Marks A constructor, field, setter method or Config method as to being autowired by Spring ' s dependency Injection Faciliti Es.


@Target ({elementtype.constructor, Elementtype.field, Elementtype.method, elementtype.annotation_type}) @ Retention (retentionpolicy.runtime) @Documented public @Interface  autowired {     /**      * Declares whether the annotated dependency is required.     * <p>defaults to {@code  true}.      */    Boolean default true ;}

2.1 @Target

First, what role does @Target play? Let's look at the description of the JDK:

Indicates the kinds of program element to which a annotation type is applicable. If a Target meta-annotation is not present in an annotation type declaration, the declared type could be used on any program Element. If such a meta-annotation is present, the compiler would enforce the specified usage restriction.

Second, @Target definition:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type)  public @Interface  Target {    elementtype[] value ();}

The annotations indicate which program elements apply, and the program elements are as follows:

 Public enumElementType {/**Class, interface (including annotation type), or enum declaration*/TYPE,/**Field declaration (includes enum constants)*/FIELD,/**Method Declaration*/METHOD,/**Parameter Declaration*/PARAMETER,/**Constructor Declaration*/CONSTRUCTOR,/**Local Variable Declaration*/local_variable,/**Annotation Type declaration*/Annotation_type,/**Package Declaration*/Package }

Finally, target is used in the following way:

@Target (Value={annotation_type})

2.2 @Retention

First, the effect: Indicates how long annotations with the annotated type is to be retained. If No Retention annotation is present on a annotation type declaration, the Retention policy defaults to Retentionpolicy. CLASS

In a nutshell, it's scope.

Then we look at the definition:

@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type)  public @Interface  Retention {    retentionpolicy value ();}

Finally, how to use:

@Retention (Value=retentionpolicy)

retentionpolicy Scope definition

 Public enumRetentionpolicy {/*** Annotations is to being discarded by the compiler. */SOURCE,/*** Annotations is to being recorded in the class file by the compiler * and need not being retained by the VM at RU  N Time.     This is the default * behavior. */CLASS,/*** Annotations is to being recorded in the class file by the compiler and * retained by the VM at run time, so T     Hey may be read reflectively. *     * @seejava.lang.reflect.AnnotatedElement*/RUNTIME}

[Email protected]

Role:indicates that annotations with a type is to is documented by Javadocand similar tools by default. This type should is used to annotate thedeclarations of types whose annotations affect the use of annotatedelements by their clients. If a type declaration is annotated withdocumented, its annotations become part of the public APIof the annotated elements. Simply, it can be part of the API.


@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type)  public @Interface  documented {}

Use: @Documented

3. Annotations implement the registration of class Autowiredannotationbeanpostprocessor

Its registration process is as follows:

The registered note-related processor code is as follows:

/*** Register all relevant annotation post processors in the given registry. * @paramregistry the registry to operate on *@paramsource The configuration source element (already extracted) * that this registration is triggered from. May is {@codenull}. * @returna Set of beandefinitionholders, containing all beans definitions * that has actually been registered by the This call */     Public StaticSet<beandefinitionholder>registerannotationconfigprocessors (Beandefinitionregistry Registry, Object source) {Defaultlistab Lebeanfactory beanfactory=Unwrapdefaultlistablebeanfactory (registry); if(Beanfactory! =NULL) {            if(! (Beanfactory.getdependencycomparator ()instanceofannotationawareordercomparator))            {Beanfactory.setdependencycomparator (annotationawareordercomparator.instance); }            if(! (Beanfactory.getautowirecandidateresolver ()instanceofcontextannotationautowirecandidateresolver)) {Beanfactory.setautowirecandidateresolver (Newcontextannotationautowirecandidateresolver ()); }} Set<BeanDefinitionHolder> beandefs =NewLinkedhashset<beandefinitionholder> (4); if(!registry.containsbeandefinition (Configuration_annotation_processor_bean_name)) {Rootbeandefinition def=NewRootbeandefinition (configurationclasspostprocessor.class);            Def.setsource (source);        Beandefs.add (Registerpostprocessor (Registry, Def, Configuration_annotation_processor_bean_name)); }        if(!registry.containsbeandefinition (Autowired_annotation_processor_bean_name)) {Rootbeandefinition def=NewRootbeandefinition (autowiredannotationbeanpostprocessor.class);            Def.setsource (source);        Beandefs.add (Registerpostprocessor (Registry, Def, Autowired_annotation_processor_bean_name)); }        if(!registry.containsbeandefinition (Required_annotation_processor_bean_name)) {Rootbeandefinition def=NewRootbeandefinition (requiredannotationbeanpostprocessor.class);            Def.setsource (source);        Beandefs.add (Registerpostprocessor (Registry, Def, Required_annotation_processor_bean_name)); }        //Check for JSR-250 support, and if present add the Commonannotationbeanpostprocessor.        if(Jsr250present &&!)registry.containsbeandefinition (Common_annotation_processor_bean_name)) {Rootbeandefinition def=NewRootbeandefinition (commonannotationbeanpostprocessor.class);            Def.setsource (source);        Beandefs.add (Registerpostprocessor (Registry, Def, Common_annotation_processor_bean_name)); }        //Check for JPA support, and if present add the Persistenceannotationbeanpostprocessor.        if(Jpapresent &&!)registry.containsbeandefinition (Persistence_annotation_processor_bean_name)) {Rootbeandefinition def=Newrootbeandefinition (); Try{def.setbeanclass (Classutils.forname (Persistence_annotation_processor_class_name, Annotationconfigutils.class. getClassLoader ())); }            Catch(ClassNotFoundException ex) {Throw NewIllegalStateException ("Cannot load optional Framework class:" +Persistence_annotation_processor_class_name, ex);            } def.setsource (source);        Beandefs.add (Registerpostprocessor (Registry, Def, Persistence_annotation_processor_bean_name)); }        returnbeandefs; }

Through the code, we can see that the registered note processor has:

Org.springframework.context.annotation.internalConfigurationAnnotationProcessor corresponds to Configurationclasspostprocessor

Org.springframework.context.annotation.internalAutowiredAnnotationProcessor corresponds to Autowiredannotationbeanpostprocessor

Org.springframework.context.annotation.internalRequiredAnnotationProcessor corresponds to Requiredannotationbeanpostprocessor

Org.springframework.context.annotation.internalCommonAnnotationProcessor corresponds to Commonannotationbeanpostprocessor

Org.springframework.context.annotation.internalPersistenceAnnotationProcessor corresponds to Persistenceannotationbeanpostprocessor

4. Annotation implementation class Autowiredannotationbeanpostprocessor use

Call chain for constructing methods

Abstractautowirecapablebeanfactory#createbean ()-->abstractautowirecapablebeanfactory#docreatebean ()--

Abstractautowirecapablebeanfactory#createbeaninstance ()--

Abstractautowirecapablebeanfactory#determineconstructorsfrombeanpostprocessors ()--

Autowiredannotationbeanpostprocessor#determineconstructorsfrombeanpostprocessors ()

Auto-injection of annotations based on member variables

Abstractautowirecapablebeanfactory#createbean ()-->abstractautowirecapablebeanfactory#docreatebean ()--

Abstractautowirecapablebeanfactory#populatebean ()-->autowiredannotationbeanpostprocessor# Postprocesspropertyvalues ()--

Injectionmetadata#inject ()-->autowiredfieldelement#inject ()/autowiredmethodelement#inject ()

5. Summary

The spring framework is dedicated to providing a powerful, non-intrusive solution to complex issues from the very beginning of its creation. At the beginning, Spring uses the number of XML configuration files to introduce the custom namespaces feature.

Spring 2.5 introduces a complete set of annotations as an alternative to XML-based configuration. Annotations can be used for automatic discovery of spring Management objects, dependency injection, life cycle methods, Web tier configuration, and unit/integration testing.

Spring annotations Do improve the efficiency of development, but all along, the work of spring annotations is in smattering state, the use of annotations in the process of encountering problems, but also through search or a number of attempts to verify the way, in order to better work, while there is time to how spring Annotation works this thing to do up.

Spring Annotated source code Analysis--how does autowired works?

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.