Spring Beans source interpretation of the--bean annotation (annotation)

Source: Internet
Author: User

With the introduction of spring annotations, more and more developers began to use annotations, this article will explain the mechanism of the annotations in series, do not seek thorough, but to string up the spring beans annotation of the pearl, show to everyone.

1. Common annotations for Spring beans:

Public @interface autowired: You can annotate member variables, methods, and constructors to accomplish the task of automating Assembly.

Marks a constructor, field, setter method or Config method as to is autowired by Spring ' s dependency injection facilities. Only one constructor (in max) of any given Bean class could carry this annotation, indicating the constructor to Autowire WH En used as a Spring bean. Such A constructor does not has to is public. Fields is injected right after construction of a beans, before any config methods is invoked. Such a config field does not has to is public. Config methods may have a arbitrary name and any number of arguments; Each of the those arguments is autowired with a matching beans in the Spring container. Bean Property setter Methods is effectively just a special case of such a general config method. Such config methods do not has to is public. In the case of multiple argument methods, the ' required ' parameter are applicable for  all arguments. In case of a Collection or Map dependency type, the container would autowire all beans matching the declared value type. In case  of a Map, the keys must is declared as type String and would be resolved to the corresponding bean names. Note that actual injection are performed through a beanpostprocessor which in turn means so you cannot use @Autowired to Inject references into beanpostprocessor or beanfactorypostprocessor types. Consult the Javadoc for the Autowiredannotationbeanpostprocessor class (which, by default, checks for the presence of this  annotation). since:2.5    

The public @interface the @Configurable autowire attribute in the configurable annotation allows spring to be assembled: @Configurable(autowire=Autowire.BY_TYPE) Alternatively, it @Configurable(autowire=Autowire.BY_NAME can be automatically assembled by type or by name.

Marks a class as being eligible for spring-driven configuration. Typically used with the AspectJ annotationbeanconfigureraspect.since:2.0
Value: Used to inject an spel expression, which can be placed on a field method or parameter.
Annotation at the field or Method/constructor parameter level, indicates a default value expression for the affect Ed argument. Typically used for Expression-driven dependency injection. Also supported for dynamic resolution of handler method parameters, e.g. in Spring MVC. A common use case was to assign default field values using "#{systemproperties.myprop}" style expressions. Note that actual processing of the @Value annotation are performed by a beanpostprocessor which in turn means so you Cann OT use @Value within beanpostprocessor or beanfactorypostprocessor types. Consult the Javadoc for the Autowiredannotationbeanpostprocessor class (which, by default, checks for the presence of this annotation). since:3.0   
Public @interface Qualifier: Specifies the qualification descriptor, which corresponds to the <qualifier> tag based on the XML configuration, @Qualifier the qualification descriptor, in addition to being injected by name, But more granular control over how to choose the candidate
@Qualifier (value = "qualified identifier").
This annotation is used on a field or parameter as a qualifier for candidate beans when autowiring. It may also is used to annotate, other custom annotations, can and turn be used as qualifiers. since:2.5
Public @interface Required Dependency check;
Marks a method (typically a JavaBean setter method) as being ' required ': That's, the setter method must be configured to Be dependency-injected with a value. Consult the Javadoc for the Requiredannotationbeanpostprocessor class (which, by default, checks for the Presenc E of this annotation). since:2.0 

2. Definition of the annotation bean annotatedbeandefinition

 Public Interface extends beandefinition {    /**     * Obtain the annotation metadata (as well as basic class metadata) 
    
     * for this bean definition ' s bean class.     
     @return The annotation metadata object (never {@code  null})      */     annotationmetadata getmetadata ();}

The interface inherits Beandefinition and provides a GetMetaData () method to get the annotation metadata for the bean definition.

Where Annotationmetadata defines an abstract interface for accessing annotations of a particular class, it can be accessed without the need to load the class.

 Public Interface extends Classmetadata, Annotatedtypemetadata {}
Classmetadata defines the abstract metadata for a particular class and does not need to load this class. The main methods are as follows:
String GetClassName () returns the name of the class.  boolean isinterface () returns whether the class is an interface. boolean isAbstract () returns whether the class is an abstract class. boolean Isconcrete () returns whether the class is a concrete class. boolean isfinal () returns whether the class is final class Boolean Hassuperclass () returns whether the class has a parent class String Getsuperclassname () Returns the name of the parent class and returns null if none. String[] Getinterfacenames () returns an array of inherited interfaces, if not, returns null . String[] Getmemberclassnames () returns the name of the referenced class. 

Annotatedtypemetadata defines access to specific types of annotations without the need to load classes. The main methods are:

Whether the boolean isannotated (String annotationtype) has a matching annotation type
Map<String,Object> getannotationattributes (String annotationtype,boolean classvaluesasstring) Get properties for a specific type of annotation

Annotationmetadata's standard implementation class Standardannotationmetadata, which uses standard reflection to obtain internal annotation information for the development class. The main methods are:

Annotationmetadata also has a subclass: Annotationmetadatareadingvisitor, which is a bytecode access implementation.

class extends Implements Classmetadata {}

Let's look at the visitor mode:

Defined:

The Gang of four defines, the Visitor as: "Represent an operation-be-performed on elements of an object Structur E. Visitor lets you define a new operation without changingthe classes of the elements on which it operates. " -″≤

The nature of the Visitor makes it an ideal pattern-to-plug into public APIs thus allowing their clients to perform operatio The NS on a class using a "visiting" class without has to modify the source.

The UML structure diagram is as follows:

Summary: The Vistor setting mode abstracts the state into an interface (the visitor), and the different States act as different implementations of the state (different visitors).

3. Annotation Bean Implementation Class

3.1 annotatedgenericbeandefinition

Inherited the genericbeandefinition, which adds support for annotation elements, which is an interface for annotation elements exposed through annotationbeandefinition.

Genericbeandefinition is mainly used to test the operation on the Annotatedbeandefinition, For example: in the implementation of Spring's component scan support (the default implementation class is Scannedgenericbeandefinition, it also implements the Annotatedbeandefinition interface)

3.2 configurationclassbeandefinition

Configurationclassbeandefinition is the inner class of Configurationclassbeandefinitionreader, Configurationclassbeandefinitionreader reads a set of configuration instances that are fully populated with attributes, registering beans with a given beandefinitionregistry within the context Definition This class is modified after the Beandefinitionreader layer, but does not inherit or extend the configuration class.

3.3 Scannedgenericbeandefinition

The ASM-based class parser, which is an extension of the Genericbeandefinition class, supports annotation metadata, which is implemented through the Annotatedbeandefinition interface.

4. Interpretation and processing of annotations

4.1 @Autowired Annotation Implementation Autowiredannotationbeanpostprocessor

 public  class  Autowiredannotationbeanpostprocessor extends   Instantiationawarebeanpostprocessoradapter  implements   Mergedbeandefinitionpostprocessor, priorityordered, Beanfactoryaware {}  
Autowiredannotationbeanpostprocessor indirectly inherits the Beanpostprocessor, which automatically binds the annotated Field,setter method and any configuration method. These members are injected when 5 Java annotations are detected. Spring's default annotations are @autowired and @value.
In addition: the @inject annotations of JSR-330 are also supported as an alternative to @autowired.

When the unique construction method for the Bean class has the required annotation parameter, and the required value is set to True, the constructor is automatically bound by default when it is treated as a spring bean. If multiple construction methods have non-required annotation parameters, they will be candidates for automatic binding. Construction methods with a large number of dependencies can be constructed by matching beans in the spring container, and the default constructor is used if no candidate satisfies the criteria. The annotation constructor is not necessarily public.
Field injection is done after the method is configured, this configuration field does not require a certain public
The configuration method can have arbitrary names and a variable list of parameters that are automatically injected into the matching bean in the spring container. The Bean's property setter method is only a special case of a generic configuration method. The configuration method does not require that the method must be public
Note: The default way to register Autowiredannotationbeanpostprocessor is <context:annotation-config> and <context:component-scan > XML tags, if you specify a custom autowiredannotationbeanpostprocessor bean definition, remove or close the default annotation configuration.

Among them, mergedbeandefinitionpostprocessor is defined as follows:
 Public InterfaceMergedbeandefinitionpostprocessorextendsBeanpostprocessor {/*** post-process The given merged bean definition for the specified bean. * @parambeandefinition the merged bean definition for the bean *@paramBeantype The actual type of the managed bean instance *@paramBeanname The name of the Bean*/    voidPostprocessmergedbeandefinition (rootbeandefinition beandefinition, class<?>Beantype, String beanname);}
Beanpostprocessor is a factory hook that can be customized to modify a new instance of a bean, for example: Check the marker interface or use the proxy to wrap them.
ApplicationContext can automatically identify beanpostprocessor beans in their bean containers and apply them to the bean that is created next. The generic bean factory is programmed to register post-processor and apply them to the entire bean factory the process of creating the bean.

In general, Post-processor sets the Bean property through the marker interface or similar to implementation postprocessbeforeinitialization (Java.lang.Object, java.lang.String ); Using a proxy wrapper bean typically implements Postprocessafterinitialization (Java.lang.Object, java.lang.String).

4.2 @configurable Annotation Implementation Annotationbeanwiringinforesolver

Setting the @Configurable Autowire property in the annotation allows spring to come from the assembly: @Configurable(autowire=Autowire.BY_TYPE) Alternatively @Configurable(autowire=Autowire.BY_NAME , it can be automatically assembled by type or by name.

Annotationbeanwiringinforesolver inherits from Beanwiringinforesolver,beanwiringinforesolver using configurable annotations to find which classes require automatic binding.

 Public class Implements Beanwiringinforesolver {}

The Resolvewiringinfo method of Beanwiringinforesolver is realized.

@Override Publicbeanwiringinfo resolvewiringinfo (Object beaninstance) {assert.notnull (beaninstance,"Bean instance must not being null"); Configurable annotation= Beaninstance.getclass (). Getannotation (Configurable.class); return(Annotation! =NULL? Buildwiringinfo (beaninstance, annotation):NULL); }    /*** Build The Beanwiringinfo for the given configurable annotation. * @paramBeaninstance The Bean instance *@paramannotation The configurable annotation found on the Bean class *@returnThe resolved Beanwiringinfo*/    protectedbeanwiringinfo buildwiringinfo (Object beaninstance, configurable annotation) {if(!Autowire.NO.equals (Annotation.autowire ())) {            return NewBeanwiringinfo (Annotation.autowire (). Value (), Annotation.dependencycheck ()); }        Else {            if(!"". Equals (Annotation.value ())) {                //explicitly specified bean name                return NewBeanwiringinfo (Annotation.value (),false); }            Else {                //Default bean name                return NewBeanwiringinfo (Getdefaultbeanname (beaninstance),true); }        }    }

4.3 @qualifier annotation Implementation class Qualifierannotationautowirecandidateresolver

 Public class extends Generictypeawareautowirecandidateresolver {}  Public class Implements Autowirecandidateresolver, Beanfactoryaware {}

Where Autowirecandidateresolver is a policy interface that determines whether a particular bean definition can be used as an automatic binding candidate for a particular dependency, its main methods are:

Boolean isautowirecandidate (Beandefinitionholder bdholder, Dependencydescriptor descriptor)

Object getlazyresolutionproxyifnecessary (dependencydescriptor descriptor,string beanname)

Object Getsuggestedvalue (Dependencydescriptor descriptor)

Qualifierannotationautowirecandidateresolver indirectly implements the Autowirecandidateresolver, the field or parameter and bean to be bound automatically. The definition is matched according to @qualifier annotations. It is also supported to bind the value of an expression by @value annotations.

In addition, it is only the javax.inject.Qualifier annotation of JSR-330.

4.4 @required annotations Implement class Requiredannotationbeanpostprocessor.

 Public class extends Instantiationawarebeanpostprocessoradapter         Implements mergedbeandefinitionpostprocessor, priorityordered, Beanfactoryaware {}

Like Autowiredannotationbeanpostprocessor, indirectly inherits from Beanpostprocessor, which adds constraints to JavaBean property configuration, and Java 5 Annotations can detect the Bean's Required property , Spring is @required annotations by default.

Note: The default way to register Autowiredannotationbeanpostprocessor is <context:annotation-config> and <context: component-scan> XML tags, if you specify a custom
The default way to register Autowiredannotationbeanpostprocessor is <context:annotation-config> and <context:component-scan> XML tag, if you specify a custom autowiredannotationbeanpostprocessor bean definition, remove or close the default annotation configuration. The rest is similar to autowiredannotationbeanpostprocessor, not to repeat them.

4.5 Annotation Implementation Class initdestroyannotationbeanpostprocessor for initialization and destruction methods

 Public class initdestroyannotationbeanpostprocessor         Implements destructionawarebeanpostprocessor, Mergedbeandefinitionpostprocessor, priorityordered, Serializable {}

Initdestroyannotationbeanpostprocessor indirectly inherits the Beanpostprocess and implements the method of initializing and destroying annotations. is the annotation implementation of Spring's Initializingbean and Disposablebean callback interfaces.

It checks the specified annotation type through the "Initannotationtype" and "Destroyannotationtype" properties, and any custom annotations can be used.

Initialization and destruction annotations can be used in any of the visible methods: public,package-protected,protected,private, etc. Although you can annotate multiple methods, we recommend that you annotate only one initialization and destruction method.

Summary:

Spring3 's annotation-based implementation of bean Dependency Injection supports the following three types of annotations:
Spring comes with a dependency injection annotation: Spring comes with a set of dependency injection annotations;
JSR-250 Annotations: Public annotations of the Java platform are one of the Java EE 5 specifications, which are included by default in JDK6, starting with Spring2.5 support.
JSR-330 Note: Java Dependency Injection Standard, one of the Java EE 6 specifications, may be added to the future JDK version, starting from Spring3 support;

which
Spring comes with Dependency injection annotations

1 @Required: Dependency check;
2 @Autowired: Automatic Assembly 2
Automated Assembly to replace automated assembly based on XML configuration
Automatic assembly based on @autowired, which is injected by type by default and can be used for constructors, fields, method injection
3 @Value: Inject Spel expression
Used to inject spel expressions that can be placed on a field method or parameter
@Value (Value = "Spel expression")
@Value (Value = "#{message}")
4 @Qualifier: Qualifier descriptor for fine-grained selection of candidates
@Qualifier qualifier descriptors can be injected in addition to names, but finer-grained control over how to select candidates
@Qualifier (value = "Qualified identifier")


JSR-250 annotations

1 @Resource: Automatic assembly, by default according to the type of assembly, if the specified name property will be assembled according to the name, you can use the following way to specify
@Resource (name = "identifier")
field or Setter method

2 @PostConstruct and Predestroy: specifying initialization and destruction method definitions by annotations

JSR-330 annotations
1 @Inject: Equivalent to the default @autowired, except that there is no required property
2 @Named: Specifies the bean name, corresponding to the default injection of the bean name in spring's own @qualifier
3 @Qualifier: Corresponds only to the extended @qualifier qualifier descriptor annotations in spring @qualifier, which can only be extended, with no Value property

Reference documents:
1. http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/
2. http://blog.csdn.net/wangshfa/article/details/9712379




Spring Beans source interpretation of the--bean annotation (annotation)

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.