Deep understanding of various annotations in spring and deep understanding of spring annotations
Annotations in Spring can be divided into two categories:
1) annotations related to spring bean containers, or bean Factory annotations;
2) springmvc-related annotations.
Spring bean container related annotations, has been: @ Required, @ Autowired, @ PostConstruct, @ PreDestory, and Spring3.0 started to support the JSR-330 standard javax. inject. * annotation (@ Inject, @ Named, @ Qualifier, @ Provider, @ Scope, @ Singleton ).
Springmvc related annotations include: @ Controller, @ RequestMapping, @ RequestParam, @ ResponseBody, and so on.
To understand the annotations in Spring, you must first understand the annotations in Java.
1. annotations in Java
In Java 1.5, annotations are introduced. What we are most familiar with is @ Override, which is defined as follows:
/** * Indicates that a method declaration is intended to override a * method declaration in a supertype. If a method is annotated with * this annotation type compilers are required to generate an error * message unless at least one of the following conditions hold: * The method does override or implement a method declared in a * supertype. * The method has a signature that is override-equivalent to that of * any public method declared in Object. * * @author Peter von der Ahé * @author Joshua Bloch * @jls 9.6.1.4 @Override * @since 1.5 */@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}
From the annotation, we can see that @ Override is used to prompt the compiler that the method using the @ Override annotation must override the parent class or a method of the same name in java. lang. Object. We can see that @ Target and @ Retention are used in the definition of @ Override. They are called"Meta Annotation"-- Defines the annotation of the annotation, or the annotation of the annotation (dizzy ...). Let's take a look.@ Retention
/** * Indicates how long annotations with the annotated type are to * be retained. If no Retention annotation is present on * an annotation type declaration, the retention policy defaults to * RetentionPolicy.CLASS. */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value();}
@ Retention is used to indicate how long the annotation is retained. There are three values:
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME}
RetentionPolicy. SOURCE is retained at the SOURCE code level and discarded by the compiler (@ Override); RetentionPolicy. CLASS is retained by the compiler at the compiled CLASS file level but discarded by the virtual machine;
RetentionPolicy. RUNTIME is retained to the RUNTIME and can be read by reflection.
Check again@ Target:
package java.lang.annotation;/** * Indicates the contexts in which an annotation type is applicable. The * declaration contexts and type contexts in which an annotation type may be * applicable are specified in JLS 9.6.4.1, and denoted in source code by enum * constants of java.lang.annotation.ElementType * @since 1.5 * @jls 9.6.4.1 @Target * @jls 9.7.4 Where Annotations May Appear */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to */ ElementType[] value();}
@ Target is used to indicate where the annotation is used. The values include:
public enum ElementType { /** 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 * @since 1.8 */ TYPE_PARAMETER, /** * Use of a type * @since 1.8 */ TYPE_USE}
Indicate where the annotation can be used: 1) class, interface, annotation, enum; 2) attribute field; 3) method; 4) parameter; 5) constructor; 6) local variables; 7) annotation type; 8) packages
Therefore:
@Target(ElementType.METHOD)@Retention(RetentionPolicy.SOURCE)public @interface Override {}
It indicates that @ Override can only be used in methods. It is retained at the source code level, processed by the compiler, and then discarded.
There is also a frequently used meta Annotation@ Brief ented:
/** * Indicates that annotations with a type are to be documented by javadoc * and similar tools by default. This type should be used to annotate the * declarations of types whose annotations affect the use of annotated * elements by their clients. If a type declaration is annotated with * Documented, its annotations become part of the public API * of the annotated elements. */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Documented {}
Indicates whether the annotation can be processed by javadoc and kept in the document.
2. Use meta annotation to customize annotation and process custom Annotation
With the meta annotation, I can use it to customize the annotation we need. Combining custom annotations with AOP or filters is a powerful weapon. For example, you can use annotations to achieve fine-grained permission control-Use Permission Annotations on classes or methods, and then intercept and process permissions in AOP or filters. The following is an implementation of the Annotation on logon permissions:
/*** No Logon annotation */@ Target ({ElementType. METHOD, ElementType. TYPE}) @ Retention (RetentionPolicy. RUNTIME) @ Documentedpublic @ interface NoLogin {}
We have defined an annotation @ NoLogin, which can be used in methods and classes. The annotation is retained until it is run and can be read by reflection. This annotation indicates the class or method annotated by @ NoLogin, which can be accessed even if the user is not logged on. The annotation is processed as follows:
/*** Check the logon interceptor **. If you do not need to check the logon, add @ NoLogin */public class CheckLoginInterceptor implements HandlerInterceptor {private static final Logger logger = Logger to the method or controller. getLogger (CheckLoginInterceptor. class); @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if (! (Handler instanceof HandlerMethod) {logger. warn ("the current handler is not HandlerMethod =" + handler. getClass (). getName () + ", req =" + request. getQueryString (); return true;} HandlerMethod handlerMethod = (HandlerMethod) handler; String methodName = handlerMethod. getMethod (). getName (); // determine whether to check logon NoLogin noLogin = handlerMethod. getMethod (). getAnnotation (NoLogin. class); if (null! = NoLogin) {if (logger. isDebugEnabled () {logger. debug ("current operation methodName =" + methodName + "No Logon check required");} return true;} noLogin = handlerMethod. getMethod (). getDeclaringClass (). getAnnotation (NoLogin. class); if (null! = NoLogin) {if (logger. isDebugEnabled () {logger. debug ("current operation methodName =" + methodName + "No Logon check required");} return true;} if (null = request. getSession (). getAttribute (CommonConstants. SESSION_KEY_USER) {logger. warn ("current operation" + methodName + "user not logged on, ip =" + request. getRemoteAddr (); response. getWriter (). write (JsonConvertor. convertFailResult (ErrorCodeEnum. NOT_LOGIN ). toString (); // return error message return false;} return true;} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}
We have defined a login interceptor above. FirstUse reflectionTo determine whether the method is annotated with @ NoLogin:
NoLogin noLogin = handlerMethod.getMethod().getAnnotation(NoLogin.class);
Then determine whether the class is annotated with @ NoLogin:
noLogin = handlerMethod.getMethod().getDeclaringClass().getAnnotation(NoLogin.class);
If it is annotated, true is returned. If it is not annotated, the system checks whether it has been logged on. If it is not logged on, an error message is returned to the foreground and false. this is a simple example of permission Processing Using annotations and filters. Extended, we can use annotations to indicate that a method or class can only be accessed by users with certain roles or permissions, and then be judged and processed in the filter.
3. annotations related to spring bean containers
1)@ Autowired is the annotation we use most. In fact, autowire = byType is the automatic injection of dependencies Based on the type (annotation-based dependency injection), which can be used in attribute fields and methods, constructor.
2)@ Qualifier is autowire = byName, @ Autowired annotation to determine whether multiple bean types are consistent, 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 belongs to the JSR250 standard and is used for attributes and methods. It is also a byName type dependency injection. Usage: @ Resource (name = "xxBean"). @ Resource without parameters defaults the first letter of the class name is lowercase.
4)Annotation (@ inject, @ Named, @ Qualifier, @ Provider, @ Scope, @ Singleton) in the standard javax. Inject. * of the JSR-330 ). @ Inject is equivalent to @ Autowired, @ Named is equivalent to @ Qualifier, and @ Named is used in the class and @ Component function.
5)@ Component, @ Controller, @ Service, @ Repository. Different from the preceding annotations, the annotations above inject the dependent bean, these annotations are used to produce beans. These annotations are all annotated on the class, and the class is annotated into one bean in the spring bean factory. @ Controller, @ Service, @ Repository is basically @ Component with more refined semantics.
6)@ PostConstruct and @ PreDestroy are not used for dependency injection, but for bean lifecycle. Similar to init-method (InitializeingBean) destory-method (DisposableBean)
4. annotation processing in spring
The annotation processing in spring is basically done through the BeanPostProcessor implementation interface:
public interface BeanPostProcessor { Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException; Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;}
Related Processing classes: AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostProcessor, PersistenceAnnotationBeanPostProcessor, RequiredAnnotationBeanPostProcessor
These processing classes can be<Context: annotation-config/>Configure the implicit configuration to the spring container. These are all dependent on injection processing, as well as the processing of production bean annotations (@ Component, @ Controller, @ Service, @ Repository:
<Context: component-scanBase-package = "net. aazj. service, net. aazj. aop"/>
These are all done by specifying the scan path of the base package and scanning them into the spring bean container. Note that context: component-scan will also configure AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor by default. Therefore, <context: annotation-config/> can be omitted. In addition, context: component-scan can also scan @ Aspect-style AOP annotations, but you must add them to the configuration file.<Aop: aspectj-autoproxy/>.
5. Differences Between Spring annotation and JSR-330 standard Annotation: