1. 程式人生 > >AOP學習之五種通知

AOP學習之五種通知

  • 建立AOP

    • 建立package命名為com.learn.aop(根據實際情況修改)

    • 配置AOP,新建ExecutionAOP,內容如下

      @Aspect
      @Component
      public class ExecutionAop {
      
          // 切點範圍
          @Pointcut("execution(* com.learn.service..*(..))")
          public void pointcut(){ }
      
          @Before("pointcut()")
          public void before() {
              System.out.println("[email protected]
      "
      ); } @AfterReturning("pointcut()") public void afterReturning() { System.out.println("[email protected]"); } @After("pointcut()") public void after() { System.out.println("[email protected]"); } @AfterThrowing("pointcut()") public void afterThrowing
      ()
      { System.out.println("[email protected]"); } @Around("pointcut()") public Object around(ProceedingJoinPoint pjp) throws Throwable { Object result; System.out.println("[email protected]前----------------"); try { result = pjp.proceed(); } catch
      (Throwable throwable) { System.out.println("[email protected]異常----------------"); // 監聽引數為true則丟擲異常,為false則捕獲並不丟擲異常 if (pjp.getArgs().length > 0 && !(Boolean) pjp.getArgs()[0]) { result = null; } else { throw throwable; } } System.out.println("[email protected]後----------------"); return result; } // Around簡單示例 // @Around("pointcut()") // public Object around(ProceedingJoinPoint pjp) throws Throwable { // Object result; // System.out.println("[email protected]前----------------"); // result = pjp.proceed(); // System.out.println("[email protected]後----------------"); // return result; // } }