注解@Aspect實現AOP功能


springboot中pom引入jar

<!-- aop 切面 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

要想把一個類變成切面類,需要兩步, 
① 在類上使用 @Component 注解 把切面類加入到IOC容器中 
② 在類上使用 @Aspect 注解 使之成為切面類

 

相關代碼

@Aspect
@Component
public class AspectTest {
    /**
     * 前置通知:目標方法執行之前執行以下方法體的內容
     * @param jp
     */
    @Before("execution(* com.springboot.aop.controller.*.*(..))")
    public void beforeMethod(JoinPoint jp){
        String methodName = jp.getSignature().getName();
        System.out.println("【前置通知】the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
    }

    /**
     * 返回通知:目標方法正常執行完畢時執行以下代碼
     * @param jp
     * @param result
     */
    @AfterReturning(value="execution(* com.springboot.aop.controller.*.*(..))",returning="result")
    public void afterReturningMethod(JoinPoint jp, Object result){
        String methodName = jp.getSignature().getName();
        System.out.println("【返回通知】the method 【" + methodName + "】 ends with 【" + result + "】");
    }

    /**
     * 后置通知:目標方法執行之后執行以下方法體的內容,不管是否發生異常。
     * @param jp
     */
    @After("execution(* com.springboot.aop.controller.*.*(..))")
    public void afterMethod(JoinPoint jp){
        System.out.println("【后置通知】this is a afterMethod advice...");
    }

    /**
     * 異常通知:目標方法發生異常的時候執行以下代碼
     */
    @AfterThrowing(value="execution(* com.springboot.aop.controller.*.*(..))",throwing="e")
    public void afterThorwingMethod(JoinPoint jp, NullPointerException e){
        String methodName = jp.getSignature().getName();
        System.out.println("【異常通知】the method 【" + methodName + "】 occurs exception: " + e);
    }

  /**
   * 環繞通知:目標方法執行前后分別執行一些代碼,發生異常的時候執行另外一些代碼
   * @return
   */
  @Around(value="execution(* com.springboot.aop.controller.*.*(..))")
  public Object aroundMethod(ProceedingJoinPoint jp){
      String methodName = jp.getSignature().getName();
      Object result = null;
      try {
          System.out.println("【環繞通知中的--->前置通知】:the method 【" + methodName + "】 begins with " + Arrays.asList(jp.getArgs()));
          //執行目標方法
          result = jp.proceed();
          System.out.println("【環繞通知中的--->返回通知】:the method 【" + methodName + "】 ends with " + result);
      } catch (Throwable e) {
          System.out.println("【環繞通知中的--->異常通知】:the method 【" + methodName + "】 occurs exception " + e);
      }

      System.out.println("【環繞通知中的--->后置通知】:-----------------end.----------------------");
      return result;
  }
}
作者:胖百二
來源:CSDN
原文:https://blog.csdn.net/wellxielong/article/details/80642726
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM