自定义注解在AOP中的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daijiguo/article/details/84778257

以下介绍面向切面编程的两种主要方式:


一、使用execution定义pointcut方式

1、定义切面
@Aspect
@Component
public class LogIntercept {

//  com.example.demo包下任意公共的(public)方法————解析切入点:public表示操作方法的权限,第一个*表示返回值,com.glodon.action表示报名,..表示子包,第二个*表示类,第三个*表示方法名称,(..)表示参数
    @Pointcut(value="execution(public * com.example.demo..*.*(..))")
    public void writeLog() {
    }
//    前置拦截,在执行目标方法之前的操作
    @Before("writeLog()")
    public void before() {
        this.printLog("@Before 方法执行前——————做日志");
    }
//   环绕拦截,在执行目标方法的前后的操作
    @Around("writeLog()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        this.printLog("@Around 方法执行前——————做日志");
        pjp.proceed();
        this.printLog("@Around 方法执行后——————做日志");
    }
//      后置拦截,在执行目标方法之前的操作
    @After("writeLog()")
    public void after() {
        this.printLog("@After 方法执行后——————做日志");
    }

    private void printLog(String str) {
        System.out.println(str);
    }
}
2、使用切面
@RestController
public class TestController {
    @GetMapping("/test")
    public String test() {
        return "hello";
    }
}

二、使用注解定义pointcut方式

1、定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AroundTest {
    String name() default "测试";
}
2、定义切面
@Component
@Aspect
public class AroundTestInteceptor {
    public AroundTestInteceptor(){
    }

  /**
   * 定义切入点
   */
  @Pointcut(value="@annotation(com.example.demo.AroundTest)")
    public void logAnnotatedMethod() {
    }

    /**
     * 拦截方法
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("logAnnotatedMethod()")
    public void inteceptorAction(ProceedingJoinPoint pjp) throws Throwable {
        Object o = null;
        MethodSignature joinPointObject = (MethodSignature) pjp.getSignature(); 
        Method method = joinPointObject.getMethod();   
        AroundTest annotation = method.getAnnotation(AroundTest.class); 
        Date enterDate = new Date();
        System.out.println("开始执行方法:" + annotation.name());
        //用于执行委托对象的目标方法
        o = pjp.proceed();
        Date leaveDate = new Date();
        System.out.println("结束执行方法:"+ annotation.name() +",方法执行的时间:" + (leaveDate.getTime() - enterDate.getTime()));
    }
}
3、使用切面
@Component
public class PowerBoot implements ApplicationRunner {
    private int i = 0;
    @Override
    @AroundTest
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("自启动开启");
    }
}

参考:
http://www.imooc.com/article/2670

猜你喜欢

转载自blog.csdn.net/daijiguo/article/details/84778257