spring --解析自定義注解SpringAOP(配合@Aspect)


1:首先,聲明自定義注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface DtTransactional {
   
   /*
    * Whether need to rollback
    */
   public boolean includeLocalTransaction() default true;
   
   public boolean confirmMethodExist() default true;
   
   /*
    * Allow [confirmMethod] is null if [confirmMethodExist] is false
    */
    public String confirmMethod() default "";

    public String cancelMethod();
    
}

自定義注解定義的屬性方法,如果沒有 default “” ,則使用該注解時該屬性為必填 ;

2:定義切面處理類

@Aspect
@Component
@Slf4j
public class DistributedTransactionAspect{
    
    @Autowired
    private DistributedTransactionInterceptor distributedTransactionInterceptor;

    @Pointcut("@annotation(com.sysware.cloud.commons.dts.annotation.DtTransactional)")
    public void distributedTransactionService() {

    }

    @Around("distributedTransactionService()")
    public Object interceptDtTransactionalMethod(ProceedingJoinPoint pjp) throws Throwable {
        log.debug("interface-ITransactionRunning-start---->");
        Object obj =  distributedTransactionInterceptor.interceptDtTransactionalMethod(pjp);
        log.debug("interface-ITransactionRunning-end---->");
        return obj;
    }
}

定義切面處理類關鍵點:

  1:類上面用@Aspect 注解修飾 。

       2:定義切點,用@Pointcut("@annotation(com.sysware.cloud.commons.dts.annotation.DtTransactional)") 注解定義切點,

  表示掃描所有用@DtTransactional注解標識的方法 。

       3:用@Around @Before @After 注解標識,標識攔截方法的時機 ;@Before是在所攔截方法執行之前執行一段邏輯。

  @After 是在所攔截方法執行之后執行一段邏輯。@Around是可以同時在所攔截方法的前后執行一段邏輯。

       4:參數ProceedingJoinPoint pjp 通過pjp 可以獲取注解信息,注解的參數,方法名,方法參數類型,方法參數等數據,然后對數據做一些統一處理。


免責聲明!

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



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