Detailed explanation of java annotations and custom annotations

definition

Annotation is a new feature introduced after JDK1.5 located in ​java.lang.annotation​. Annotation is actually a special mark to the code. These marks can be read during compilation, class loading and runtime, and executed accordingly的处理。 Treatment.

Third-party annotations

For Java developers, JDK comes with some annotations, and there are a lot of annotations in the third-party framework Spring. These annotations are called third-party annotations.

1. Jdk general notes

  1. @Override annotation: Compile check, tell the compiler that this is a method of overriding the parent class. If the parent class deletes this method, the child class will report an error.

@Target({ElementType.METHOD})

@Retention(RetentionPolicy.SOURCE)

public @interface Override {

}

  1. @Deprecated annotation: Compile check, indicating that the annotated element has been deprecated

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD,

                ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE})

public @interface Deprecated {

}

The above two annotations are removed and there is nothing except some meta-annotations, but after we add these two annotations, the compiler can recognize it, and it can be understood as a label, it has no actual logical processing , And the user who implements the logic is the annotation user. It is essentially a "marked annotation", which is only known by the compiler, and this is how annotations work.

The essence of annotation is an interface , which inherits the java.lang.annotation.Annotation interface by default.

public interface Annotation {

        boolean equals(Object var1);

 

        int hashCode();

 

        String toString();

 

        Class<? extends Annotation> annotationType();

}

 

2. Meta annotation

Meta annotations are used to annotate other annotations. Java 5.0 defines 4 standard meta-annotations, as follows:

  1. @Target
  1. @Retention
  1. @Documented
  1. @Inherited

 

2.1@Target

The @Target annotation is used to declare the scope of the annotation, for example, the scope of the annotation is class, interface, method, etc. Source code:

package java.lang.annotation;

 

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.ANNOTATION_TYPE})

public @interface Target {

        ElementType[] value();

}

The ElementType indicates where the annotation can be used:

public enum ElementType {

        TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE;

}

Specific explanation:

enumerate effect
ElementType.PACKAGE Annotations are used in packages
ElementType.TYPE Annotations act on types (classes, interfaces, annotations, enumerations)
ElementType.ANNOTATION_TYPE Annotations act on annotations
ElementType.CONSTRUCTOR Annotations act on construction methods
ElementType.METHOD Annotations act on methods
ElementType.PARAMETER Annotations act on method parameters
ElementType.FIELD Annotations act on attributes
ElementType.LOCAL_VARIABLE Annotations act on local variables

2.2@Retention

The function of the @Retention annotation is to specify the life cycle of the annotation. For example, it can be processed at compile time and can be processed at runtime. Source code:

@Documented

@Retention(value = RetentionPolicy.RUNTIME)

@Target(value = {ElementType.ANNOTATION_TYPE})

public @interface Retention {

        public RetentionPolicy value();

}

 

Its enumeration class is ​RetentionPolicy​, and there are only three optional values

 

enumerate effect
RetentionPolicy.SOURCE Keep in the source code, can be processed during compile time
RetentionPolicy.CLASS Keep in the Class file, which can be processed when the Class is loaded
RetentionPolicy.RUNTIME Retained during operation, can be processed during operation

2.3@Documented

Is a mark annotation, the annotation with this annotation will be retained in the generated java document

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.ANNOTATION_TYPE})

public @interface Documented {

}

 

2.4@Inherited

The annotation modified by the @Inherited annotation is inheritable, that is, if we modify a class with @Inherited, then the subclasses of this class will inherit this annotation by default.

@Documented

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.ANNOTATION_TYPE})

public @interface Inherited {

}

 

Custom annotation

When the third-party annotations cannot meet our business requirements, we need to write the annotations ourselves. At this time, it is a custom annotation.

1.1, custom annotation syntax

In the annotations, four kinds of meta-annotations are needed to declare the scope of the annotation, life cycle, inheritance, whether to generate documents, etc. In addition, annotations can also have their own member variables. If an annotation has no member variables, it is called a mark annotation.

 

@Retention(RetentionPolicy.RUNTIME)

@Target({ ElementType.METHOD })

@Documented

public @interface CxmAction {

    String code() default "";// 权限码

String descrption() default "";// 描述

 

String prompt() default ""; // 权限提示

}

 

1.2. Annotation instructions

1.2.1, AOP + annotation

Using AOP is a common processing method, the first choice, you need to define the aspect class

@Aspect

@Component

@Slf4j

@Order(-1)

public class CxmLogbackAspect {

 

/***

 * 定义controller切入点拦截规则,拦截SystemLog注解的业务方法

 */

@Pointcut("@annotation(com.cxm.common.annotation.SystemLog)")

public void logPointcut(){

 

}

 

/**

 * 环绕

 * @param proceedingJoinPoint

 * @return

 * @throws Throwable

 */

@Around("logPointcut()")

public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

    // 执行具体的业务逻辑

}

 

}

 

  • 1.2.2, HandlerInterceptor + annotation

Using Spring's interceptor HandlerInterceptorAdapter, annotated services can also be implemented. For example, in the system, this method is used in conjunction with SkipCertification to achieve the function of skipping token verification for certain specified interfaces.

@Slf4j

@Component

public class PermissionInterceptor extends HandlerInterceptorAdapter {

 

/**

 * 

  * @Title: preHandle 

  * @Description: 在Controller执行之前调用,如果返回false,controller不执行

  * @param  @param request

  * @param  @param response

  * @param  @param handler

  * @param  @return

  * @param  @throws Exception 

  * @throws 

  *

 */

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    if (!(handler instanceof HandlerMethod)) {// 如果不是HandlerMethod而是静态资源的请求,就直接跳过去

        return true;

    }

    HandlerMethod method = (HandlerMethod) handler;

    SkipCertification  certification = method.getMethodAnnotation(SkipCertification.class);

    if (null != certification) {// 跳过token验证

        return true;

    } else {

         // 执行校验  

    }

}

 

}

 

1.2.3, java reflection + annotation

Through reflection, you can get annotated attribute values

public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {

    TestAnnotation testAnnotation = new TestAnnotation();

    Field[] fields = obj.getClass().getDeclaredFields();

      for(Field field : fields) {

          field.setAccessible(true);

          if(field.isAnnotationPresent(testAnnotation )) {

              map.put(field.getName(),field.get(obj));

           }

        }

    }

 

1.2.4, Filter + annotation

You can also use filters to achieve direct functions, such as using fastJSON's AfterFilter to achieve attribute enhancement

public void doWrite(List<Field> fields, Object object) {

    for (int i = 0; i < fields.size(); i++) {

        Field field = fields.get(i);

        Stall stallAnn = AnnotationUtils.getAnnotation(field, Stall.class);

        if (stallAnn != null) {

                Object value = ReflectionUtils.getField(field, object);

                if (value != null) {

                        this.doWrite(field, value);

                }

        }

    }

}

Guess you like

Origin blog.csdn.net/Crystalqy/article/details/106146818