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 可以獲取注解信息,注解的參數,方法名,方法參數類型,方法參數等數據,然后對數據做一些統一處理。