1. 程式人生 > >自定義註解在AOP中的應用

自定義註解在AOP中的應用

以下介紹面向切面程式設計的兩種主要方式:


一、使用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