Use custom annotations in SpringBoot projects

    Custom annotations are often encountered in SpringBoot projects, and the classes, methods or properties that use them need to be operated according to the annotations. The following is mainly to use the interceptor method for annotation interception judgment, here is mainly to use the pom method for development.

1. Because it is the interceptor used, the reference of spring-boot-starter-web must be imported:

 

 

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
    </parent>

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

 

 

2. Customize an annotation:

 

 

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

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description customize an annotation
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggerAnnotation {
}

 

 

3. Customize an interceptor for annotation interception:

 

 

import com.annotation.log.LoggerAnnotation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description implements custom logging through interceptors
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter{

    private Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //Get the specified annotation on the current method
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //Check if the current annotation exists
        if(loggerAnnotation != null){
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime",startTime);
            logger.info("The time to enter" + method.getName() + "method is: " + startTime);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //Get the specified annotation on the current method
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //Check if the current annotation exists
        if(loggerAnnotation != null){
            long endTime = System.currentTimeMillis();
            long startTime = (Long) request.getAttribute("startTime");
            long periodTime = endTime - startTime;
            logger.info("Leave" + method.getName() + "The time of the method is: " + endTime);
            logger.info("The duration of the " + method.getName() + " method is: " + periodTime);
        }
    }
}

 

 

4. Inject the interceptor class into the adapter, otherwise the access cannot be intercepted normally.

 

 

import com.annotation.interceptor.LoggerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description register a custom interceptor
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorRegister extends WebMvcConfigurerAdapter {



    @Bean
    public LoggerInterceptor loggerInterceptor(){
        return new LoggerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(loggerInterceptor());
    }

}

 

 

5. Define a restful class for testing:

 

 

import com.annotation.log.LoggerAnnotation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liaoyubo
 * @version 1.0 2017/9/14
 * @description
 */
@RestController
public class LoginController {

    @RequestMapping("/login")
    @LoggerAnnotation
    public void login(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }

}

 

 

Start the project and get the following by accessing the connection address http://localhost:8080/annotationTest

The output result:

2017-09-15 13:52:27.015 INFO 407336 --- [nio-8080-exec-1] cainterceptor.LoggerInterceptor : The time to enter the login method is: 1505454747015  
2017-09-15 13:52:32.202 INFO 407336 --- [nio-8080-exec-1] cainterceptor.LoggerInterceptor: The time to leave the login method is: 1505454752202  
2017-09-15 13:52:32.202 INFO 407336 --- [nio-8080-exec-1] cainterceptor.LoggerInterceptor: The duration of the login method is: 5187

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326797539&siteId=291194637