In-depth understanding of various annotations in spring

Source: Internet
Author: User

The annotations in spring can be divided into two main categories:

1) Spring bean Container-related annotations, or bean factory-related annotations;

2) SPRINGMVC related annotations.

Spring's bean container-related annotations are: @Required, @Autowired, @PostConstruct, @PreDestory, and the JSR-330 standard that Spring3.0 started to support javax.inject.* Notes in (@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton).

SPRINGMVC related notes are: @Controller, @RequestMapping, @RequestParam, @ResponseBody and so on.

To understand the annotations in spring, first understand the annotations in Java.

1. Annotations in Java

In Java 1.5, the introduction of annotations, we are most familiar with is: @Override, it is defined as follows:

/*** Indicates that a method declaration was intended to the override A * method declaration in a supertype.  If a method is annotated with * This annotation type compilers be required to generate an error * message unless at least One of the following conditions hold: * The method is does override or implement a method declared in a * supertype. * The method has a signature, that's override-equivalent to, of * any public method declared in Object. * * @authorPeter von der ahé *@authorJoshua Bloch * @jls 9.6.1.4 @Override *@since1.5*/@Target (Elementtype.method) @Retention (Retentionpolicy.source) Public@InterfaceOverride {}

From the comments, we can see that the function of the @Override is to prompt the compiler that the method using the @override annotation must override the parent class or a method of the same name in the Java.lang.Object. We see the use of @Target in the definition of @override, @Retention, they are so-called " Meta annotations "-that is, annotations that define annotations , or annotations that annotate annotations (Halo ...). Let's look at the @Retention .

 /**   * indicates how long annotations with the  Annotated type is to * is retained. If No Retention annotation is present on * a annotation type declaration, the Retention policy defaults to * Retentionpol Icy. CLASS.  */  @Documented @retention ( Retentionpolicy.runtime) @Target (elementtype.annotation_type)  public  @interface   Retention { /**   * Returns the retention policy. *   @return   The retention policy  Span style= "color: #008000;" >*/  Retentionpolicy value ();}  

@Retention is used to indicate how long an annotation is retained and there are three kinds of values:

 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}
Retentionpolicy.source remains at the source level and is discarded by the compiler (@Overrideretentionpolicy. Class is kept at the compiled class file level by the compiler, but discarded by the virtual machine;
The retentionpolicy.runtime is persisted to the runtime and can be read by reflection .

Look again at @Target:

 Packagejava.lang.annotation;/*** Indicates the contexts in which a annotation type is applicable.  The * declaration contexts and type contexts in which a annotation type may be * applicable is specified in JLS 9.6.4.1, and denoted in source code by Enum * Constants ofJava.lang.annotation.ElementType * @since1.5 * @jls 9.6.4.1 @Target * @jls 9.7.4 Where Annotations may Appear*/@Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type) Public@InterfaceTarget {/*** Returns An array of the kinds of elements an annotation type * can is applied to. * @returnAn array of the kinds of elements an annotation type * can is applied to*/elementtype[] Value ();}

@Target to indicate where the annotation is used, the values are:

 Public enumElementType {/**Class, interface (including annotation type), or enum declaration*/TYPE,/**Field declaration (includes enum constants)*/FIELD,/**Method Declaration*/METHOD,/**formal parameter declaration*/PARAMETER,/**Constructor Declaration*/CONSTRUCTOR,/**Local Variable Declaration*/local_variable,/**Annotation Type declaration*/Annotation_type,/**Package Declaration*/Package ,/*** Type Parameter declaration *@since1.8*/Type_parameter,/*** Use of a type *@since1.8*/Type_use}

Indicate where the note can be used: 1) class, interface, annotations, enum; 2) attribute domain, 3) method, 4) parameter 5) constructor; 6) local variable; 7) annotation type; 8) package

So:

@Target (Elementtype.method) @Retention (Retentionpolicy.source)  public @Interface  Override {}

Indicates that @Override can only be used on methods, kept at the source level, processed by the compiler, and then discarded.

There is also a frequently used meta-annotation @Documented :

/** * indicates that annotations with a type is to is documented by Javadoc * and similar tools by default.  This type should is used to annotate the * declarations of types whose annotations affect the use of annotated * elements By their clients.   */ @Documented @retention (retentionpolicy.runtime) @Target (elementtype.annotation_type)  public @Interface  documented {}

Indicates whether annotations can be Javadoc processed and retained in the document.

2. Use meta annotations to customize annotations and handle custom annotations

With meta annotations, I can use it to customize the annotations we need. Combining custom annotations with AOP or filters is a very powerful weapon. For example, you can use annotations to achieve fine-grained control of permissions-using permission annotations on classes or methods, and then intercepting them in an AOP or filter. The following is an implementation of an annotation about login permissions:

/***/@Target ({elementtype.method, elementtype.type}) @Retention ( Retentionpolicy.runtime) @Documented public @Interface  nologin {}

We have customized an annotation @NoLogin that can be used on methods and classes, annotations are persisted to the runtime, and can be read by reflection. The implication of this annotation is that the class or method that is @NoLogin annotated is accessible even if the user is not logged in. Here's how the annotations are processed:

/*** Check Login blocker * If you do not need to check login can add @nologin to the method or controller*/ Public classChecklogininterceptorImplementsHandlerinterceptor {Private Static FinalLogger Logger = Logger.getlogger (checklogininterceptor.class); @Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler) throwsException {if(! (HandlerinstanceofHandlermethod)) {Logger.warn ("Current operation handler not handlermethod=" + handler.getclass (). GetName () + ", req=" +request.getquerystring ()); return true; } Handlermethod Handlermethod=(Handlermethod) handler; String MethodName=Handlermethod.getmethod (). GetName (); //determine if you need to check loginNologin Nologin = Handlermethod.getmethod (). Getannotation (Nologin.class); if(NULL!=Nologin) {            if(logger.isdebugenabled ()) {Logger.debug ("Current Operation Methodname=" + MethodName + "Do not need to check login status"); }            return true; } nologin= Handlermethod.getmethod (). Getdeclaringclass (). Getannotation (Nologin.class); if(NULL!=Nologin) {            if(logger.isdebugenabled ()) {Logger.debug ("Current Operation Methodname=" + MethodName + "Do not need to check login status"); }            return true; }        if(NULL==request.getsession (). getattribute (Commonconstants.session_key_user)) {Logger.warn ("Current Operation" + MethodName + "user not logged in, ip=" +request.getremoteaddr ()); Response.getwriter (). Write (Jsonconvertor.convertfailresult (errorcodeenum.not_login). toString ()); Return error messagereturn false; }        return true; } @Override Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Modela Ndview Modelandview)throwsException {} @Override Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object Handl Er, Exception ex)throwsException {}}

Above we define a login interceptor, first using reflection to determine whether the method is @NoLogin annotated:

Nologin Nologin = Handlermethod.getmethod (). Getannotation (Nologin.  Class); 

then judge whether the class is @NoLogin annotated:

Nologin = Handlermethod.getmethod (). Getdeclaringclass (). Getannotation (Nologin.  Class); 

If it is annotated, it returns true, and if it is not annotated, it is determined if it is already logged in and returns an error message to the foreground and false if not logged in. This is a simple example of using annotations and filters for permission handling. Extension, then we can use annotations to represent a method or class that can only be accessed by a user who has a certain role, or who has some kind of permission, and then is judged in the filter.

3. Spring's bean container-related annotations

1)@Autowired is the most used annotation, in fact Autowire=bytype is based on the type of automatic injection dependency (annotation-based dependency injection), can be used in the domain, method, constructor.

2)@Qualifier is autowire=byname, @Autowired annotation to judge multiple bean types, you need to use @Qualifier ("Xxbean") to specify the ID of the dependent bean:

@Controller @requestmapping ("/user")  Public class Hellocontroller {    @Autowired    @Qualifier ("UserService")    Private UserService UserService;

3)@Resource belong to the JSR250 standard for attribute domain amounts and methods. is also a dependency injection of the byname type. How to use: @Resource (name= "Xxbean"). The @Resource default class name with no parameters is the lowercase first letter.

4) Annotations in the JSR-330 standard javax.inject.* (@Inject, @Named, @Qualifier, @Provider, @Scope, @Singleton). @Inject is equivalent to @autowired, @Named is equivalent to @Qualifier, and @Named used on classes with @Component functions.

5)@Component, @Controller, @Service, @Repository, these annotations are different from the annotations above, and the annotations above are injected into the dependent bean, and these annotations are used to produce beans, These annotations are annotations on the class, and the class is annotated into a bean in the Spring bean factory. @Controller, @Service, @Repository is basically a @component with more refined semantics.

6)@PostConstruct and @PreDestroy are not for dependency injection, but for the bean's life cycle. Similar to Init-method (Initializeingbean) Destory-method (Disposablebean)

4. Processing of annotations in spring

The processing of annotations in spring is basically done by implementing interface Beanpostprocessor:

 Public Interface beanpostprocessor {    throws  beansexception;     throws beansexception;}

The related processing classes are: Autowiredannotationbeanpostprocessor,commonannotationbeanpostprocessor, Persistenceannotationbeanpostprocessor, Requiredannotationbeanpostprocessor

These processing classes can be configured implicitly in the <context:annotation-config/> configuration into the spring container. These are the processing of dependency injections, as well as the handling of production bean annotations (@Component, @Controller, @Service, @Repository):

<context:component-scan base-package= "Net.aazj.service,net.aazj.aop"/>

These are done by specifying the scan's base package path and scanning them into the spring bean container. Note Context:component-scan will also default to Autowiredannotationbeanpostprocessor,commonannotationbeanpostprocessor configuration in. So the <context:annotation-config/> can be omitted. In addition, Context:component-scan can also scan @aspect-style AOP annotations, but you need to include <aop:aspectj-autoproxy/> in the configuration file for mates.

5. The difference between spring annotations and JSR-330 standard annotations :

In-depth understanding of various annotations in spring

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.