Talking about custom annotation and usage scene in Java

Time:2020-10-26

True cultivation does not pursue any specific purpose, just like all the efforts made for self-improvement, it is meaningful in itself.

The general usage scenario of Java custom annotation is: Custom annotation + interceptor or or AOP. The framework is designed by using custom annotation to make the code look very elegant. This article will start from the basic concept of custom annotation, and then start the actual combat, write a small piece of code to achieve custom annotation + interceptor, custom annotation + AOP.

1、 What is annotation

What are Java annotations? Here’s a reference from Wikipedia

Java annotation, also known as Java annotation, is a special syntax metadata supported by jdk5.0.

Classes, methods, variables, parameters and packages in Java language can be annotated. Unlike Javadoc, Java annotations can obtain annotation content through reflection. Annotations can be embedded in bytecode when the compiler generates class files. The Java virtual machine can keep the annotation content and get the annotation content at runtime. Of course, it also supports custom Java annotations.

2、 Annotation system diagram

Meta notes: java.lang.annotation Meta annotations are provided in. You can use these annotations to define your own annotations. Target and retention annotations are mainly used

Talking about custom annotation and usage scene in Java

Annotation processing class: since the annotation is defined above, there must be a way to get the annotation defined by us. java.lang.reflect The. Annotationelement interface provides this functionality. Annotations are processed through java reflection.

As follows, the class, method and field related to reflection implement the annotationelement interface.

Talking about custom annotation and usage scene in Java

Talking about custom annotation and usage scene in Java

Therefore, as long as we get the class, method and field class through reflection, we can pass thegetAnnotation(Class<T>)Get the annotation we want and take the value.

3、 Common meta annotations

Target: describes the scope of the object modified by annotation. The value is in java.lang.annotation . ElementType definition, commonly used include:

  • Method: used to describe the method
  • Package: used to describe packages
  • Parameter: used to describe method variables
  • Type: used to describe a class, interface, or enum type

Retention: indicates how long the annotation is retained. Value in java.lang.annotation . retentionpolicy, the value is:

  • Source: valid in the source file and will be ignored during compilation
  • Class: compiled with source file in class file, ignored at runtime
  • Runtime: valid at runtime

Only defined as RetentionPolicy.RUNTIME Only then can we get the annotation through annotation reflection.

Therefore, suppose we want to customize an annotation, which is used on the field and can be obtained through reflection. The function is to describe the length and function of the field.

@Target( ElementType.FIELD )/ / comments are used on fields

4、 Example – Reflection get annotation

First define a note:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyField {
    String description();
    int length();
}

Get annotations by reflection

public class MyFieldTest {

Operation results

Talking about custom annotation and usage scene in Java

Application scenario 1: user defined annotation + interceptor to realize login verification

Next, we use the springboot interceptor to implement such a function. If @ loginrequired is added to the method, the user will be prompted that the interface needs to log in to access, otherwise no login is required.

First define a loginrequired annotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginRequired {

}

Then write two simple interfaces to access sourcea and sourceb resources

@RestController

Successful access before adding interceptor

Talking about custom annotation and usage scene in Java

To implement the handlerinterceptor class of spring, the interceptor is implemented first, but not intercepted, and the log is simply printed, as follows:

public class SourceAccessInterceptor implements HandlerInterceptor {

Implement the spring class webmvcconfigurer, create the configuration class, and add the interceptor to the interceptor chain

@Configuration
public class InterceptorTrainConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SourceAccessInterceptor()).addPathPatterns("/**");
    }
}

The interception is successful as follows

It's in the interceptor

Add our login annotation @ loginrequired to the sourceb method

@RestController

Simple implementation of login interception logic

@Override

It runs successfully. You need to log in when you access sourceb, but you don’t need to log in to access sourcea

Talking about custom annotation and usage scene in Java

Talking about custom annotation and usage scene in Java

Application scenario 2: Custom annotation + AOP to realize log printing

Import the dependency package needed by the aspect first

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Define an annotation @mylog

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLog {

}

To define an aspect class, see the following code comments for understanding:

@Aspect / / 1. Indicates that this is an aspect class

In step 2, the indexcontroller writes a source C for testing, and adds our custom annotation:

@MyLog

Start the springboot web project and enter the access address:localhost:8080/sourceC/zebinSource

Recommended Today

Java security framework

The article is mainly divided into three parts1. The architecture and core components of spring security are as follows: (1) authentication; (2) authority interception; (3) database management; (4) authority caching; (5) custom decision making; and;2. To build and use the environment, the current popular spring boot is used to build the environment, and the actual […]