SpringBoot 自定义Annotation

1. Maven pom.xml 文件添加AOP相关的jar包

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.1.RELEASE</version> <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.12</version> <scope>compile</scope>
        </dependency>

2. 自定义Annotation

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)  
public @interface SingleLocalCache {
    
    boolean cache() default false;    
    
    String key();

}

3. 写一个切面编程的方法来实现你想要的逻辑

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SingleLocalCacheAspect {
    // 在方法执行前执行
    @Before("@annotation(com.cisco.webex.config.SingleLocalCache)")
    public Object beforeExecute(JoinPoint joinPoint) {
            //MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //Method method = signature.getMethod();
            return null;
    }
     //方法返回后执行
    @AfterReturning(value = "@annotation(com.cisco.webex.config.SingleLocalCache)",
            returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("=====after return===");
        System.out.println("result: " + result.toString());
    }
    //同时处理方法执行前和执行后
    @Around("@annotation(com.cisco.webex.config.SingleLocalCache)")
    public void around(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

         //这一行会执行你的方法

         joinPoint.proceed();

        long timeTaken = System.currentTimeMillis() - startTime;
    }
  
}

4. 接下来具体使用自定义的Annotation

@CrossOrigin
@RestController
public class TestController {
    
    @RequestMapping(method = RequestMethod.GET, value="/test")
    @SingleLocalCache(cache=true,key="test")
    public String getSiteName(@RequestParam(value = "test") String test) {
         return null;
    }
  
    
}

参考文章

https://docs.spring.io/spring/docs/2.5.x/reference/aop.html

http://www.springboottutorial.com/spring-boot-and-aop-with-spring-boot-starter-aop

https://www.journaldev.com/2583/spring-aop-example-tutorial-aspect-advice-pointcut-joinpoint-annotations

猜你喜欢

转载自blog.csdn.net/gaozhiqiang111/article/details/84565242