To learn more about annotations, we must be able to define our own annotations and use them. Before we can define our own annotations, we must understand the meta annotations provided by Java and the syntax for defining annotations. Meta-annotations: Meta-annotations are responsible for making other annotations. Java5. 0Defines the4The standard meta-annotation types that are used to provide annotations for other annotation types. Java5. 0Meta-annotations for definitions:1.@Target.2.@Retention.3.@Documented.4.@InheritedThese types and the classes they support are found in the java.lang.annotation package. Let's take a look at what each meta-annotation does and how the corresponding sub-parameters are used.@Target:@TargetAnnotations can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumerated values), method parameters, and local variables (such as loop variables,catchParameters). Target is used in the Annotation type declaration to clarify the target it modifies. Function: Used to describe the scope of the annotation (i.e. where the described annotation can be used).1.CONSTRUCTOR: Used to describe the CONSTRUCTOR2.FIELD: Describes the domain3.LOCAL_VARIABLE: Used to describe local variables4.METHOD: Describes methods5.PACKAGE: Used to describe packages6.PARAMETER: describes parameters7.TYPE: Used to describe a class, interface (including annotation types), orenumExample Copy the code @Target(ElementType.TYPE)
public @interface Table {
    /** * data table name annotation, default is class name *@return* /
    public String tableName(a) default "className";
}

@Target(ElementType.FIELD)
public @interfaceNoDBColumn {} copy code annotation Table can be used for annotation classes, interfaces (including annotation types), orenumA statement, not a noteNoDBColumnCan only be used with member variables of an annotation class. @Retention: @RetentionDefines theAnnotationLength of time retained: someAnnotationAppears only in source code and is discarded by the compiler; Others are compiled inclassFile; Compiled inclassIn the fileAnnotationMay be ignored by the virtual machine while others are inclassWill be read when loaded (please note that does not affectclassBecauseAnnotationwithclassIs separated in use). Use thismeta-AnnotationCan beAnnotationThe "life cycle" limit of. Purpose: Indicates the level at which the annotation information needs to be saved, and is used to describe the annotation life cycle (i.e., the scope in which the described annotation is valid) value (RetentionPoicy) are: 1.SOURCE: valid in the source file (that is, retained in the source file) 2.CLASSIn:classValid in the file (i.eclass3).RUNTIME: valid at runtime (i.e., reserved at runtime)Retention meta-annotationThere are unique typesvalueAs a member, its value comes fromjava.lang.annotation.RetentionPolicyAn enumeration type value of. Example: Copy the code @Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
    public String name(a) default "fieldName";
    public String setFuncName(a) default "setField";
    public String getFuncName(a) default "getField"; 
    public boolean defaultDBValue(a) default false; } The RetentionPolicy value of the Column annotation is RUTIME, so that the annotation processor can reflect the value of the annotation to do some runtime logic@Documented:@DocumentedAnnotations that describe other types of annotations should be used as public apis for annotated program members, and therefore can be documented by tools such as Javadoc. Documented is a marked annotation that has no member. Copy the code@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Column {
    public String name(a) default "fieldName";
    public String setFuncName(a) default "setField";
    public String getFuncName(a) default "getField"; 
    public boolean defaultDBValue(a) default false; } Duplicate code@Inherited:@InheritedA meta-annotation is a markup annotation,@InheritedStates that an annotated type is inherited. If one is used@InheritedThe annotation type of the modifier is used for oneclass, thisannotationWill be used for thatclassThe subclass. Note: @Inherited annotationThe type is annotatedclassInherited by a subclass of. A class does not inherit from the interface it implementsannotation, the method does not inherit from the method it overloadsannotation. When the @Inherited annotationtype-labeledannotationtheRetentionisRetentionPolicy.RUNTIME, the reflectionAPIEnhances this inheritance. If we usejava.lang.reflectTo query for an @Inherited annotationThe type ofannotationReflection code checking starts work: checkingclassAnd its parent class until the specifiedannotationThe type is discovered, or reaches the top of the class inheritance structure. Example code: Copy code /** ** @author peida* * / @Inherited
public @interface Greeting {
    public enum FontColor{ BULE,RED,GREEN};
    String name(a);
    FontColor fontColor(a) default FontColor.GREEN; } Copy code custom annotations: use@interfaceCustom annotations, automatic inherited Java. Lang. The annotation. The annotation interface, the compiler automatically other details. When defining annotations, you cannot inherit from other annotations or interfaces.@interfaceTo declare an annotation, each of these methods actually declares a configuration parameter. The name of the method is the name of the parameter, and the return value type is the type of the parameter. (The return value type can only be the basic type, Class, String,enum). Can be achieved bydefaultTo declare the default values of the parameters. Define the annotation format:public @interfaceAnnotation nameSupported data types for {body} annotation parameters:1.All basic data types (int.float.boolean.byte.double.char.long.short)2.Type String3.The Class type4.enumtype5.The Annotation type6.All of these types of array Annotation types are called Annotation typespublicOr the default (default) these two access modifier. For example,String value(a); I'm going to set this method to the default defaul type; Second, parameter members can only use primitive typesbyte.short.char.int.long.float.double.booleanEight basic data types, and String, Enum, Class, annotations and other data types, and that some types of arrays. For example,String value(a); The parameter member here is String; Third, if there is only one parameter member, it is best to set the parameter name to"value"The FruitName annotation has only one parameter member. Simple custom annotations and examples of using annotations: copy codepackage annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** * Notes on fruit names *@author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
    String value(a) default ""; } Copy code Copy codepackage annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/** ** Fruit color notes *@author peida
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitColor {
    /** ** color enumeration *@author peida
     *
     */
    public enum Color{ BULE,RED,GREEN};
    
    /** * Color attribute *@return* /
    Color fruitColor(a) default Color.GREEN; } Copy code Copy codepackage annotation;

import annotation.FruitColor.Color;

public class Apple {
    
    @FruitName("Apple")
    private String appleName;
    
    @FruitColor(fruitColor=Color.RED)
    private String appleColor;
    
    
    
    
    public void setAppleColor(String appleColor) {
        this.appleColor = appleColor;
    }
    public String getAppleColor(a) {
        return appleColor;
    }
    
    
    public void setAppleName(String appleName) {
        this.appleName = appleName;
    }
    public String getAppleName(a) {
        return appleName;
    }
    
    public void displayName(a){
        System.out.println("The name of the fruit is: apple"); }} Copy the default value of the code annotation element: The annotation element must have a definite value, either specified in the default value of the annotation definition or when the annotation is used. The value of the non-primitive annotation element cannot benull. Therefore, use an empty string or0Being the default is a common practice. This constraint may make it harder for the processor to show the existence of an element or the lack of status, because each statement annotations, all elements are present, and have the corresponding values, in order to circumvent this constraint, we can define some special values, such as an empty string or negative, said an element does not exist at a time, when the custom annotation, it has become a habit. Such as:package annotation;
  
  import java.lang.annotation.Documented;
  import java.lang.annotation.ElementType;
  import java.lang.annotation.Retention;
  import java.lang.annotation.RetentionPolicy;
  import java.lang.annotation.Target;
  
  /** * Notes from fruit supplier *@author peida
  *
  */
 @Target(ElementType.FIELD)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 public @interface FruitProvider {
     /** * Supplier number *@return* /
     public int id(a) default- 1;
     
     /** * Supplier name *@return* /
     public String name(a) default "";
     
     /** * Supplier address *@return* /
     public String address(a) default ""; } defines annotations and adds annotation information to related classes and class attributes as needed. Without a responsive annotation information processing process, annotations can be said to be useless. How to make annotations play a role, mainly lies in the annotation processing method, next we will learn the annotation information acquisition and processing! Annotate using interceptors write interceptor path configuration using interceptors@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private Environment env;

    @Autowired
    private UrlAuthInterceptor urlAuthInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // All intercepts are ok, as long as there are no permissions annotations
        registry.addInterceptor(urlAuthInterceptor).addPathPatterns("/ * *").excludePathPatterns("/".""); }}/** * Permission authentication interceptor *@author huzhihui
 * @version$: v 0.1 2018 2018/3/23 13:28 huZHIhui Exp $$*/
@Component
public class UrlAuthInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(UrlAuthInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(o instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) o;
            //-- get the annotation
            UrlAuth urlAuth = handlerMethod.getMethodAnnotation(UrlAuth.class);
            if(null! = urlAuth){//-- Todo handles business}}return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}@Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}}Copy the code