自定義注解搭配AOP使用

首先敘述一下業(yè)務(wù),在每個模塊中達(dá)到某要求時都要給當(dāng)前用戶添加積分,所以這里用到了注解搭配AOP。

首先自定義一個注解

/**
 * @author zhangGX
 * @date 2021-01-06 16:40
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AddPoint {

    /**
     * 是否入庫
     * @return
     */
    boolean  add() default true;
}
/**
 * @author zhangGX
 * @date 2021-01-06 16:41
 */
@Aspect
@Component
public class AddPointAspect {
    private static final Logger logger = LoggerFactory.getLogger(AddPointAspect.class);

    //切入點(diǎn)是自定義注解類的地址
    @Pointcut("@annotation(org.cqbanxi.smartcity.common.biz.anno.AddPoint)")
    public void aspect() {
    }

    @Around("aspect()")
    public void addPoint(ProceedingJoinPoint point) throws Throwable {
        //執(zhí)行調(diào)用者類中的方法
        point.proceed();

        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        //獲取注解中的屬性  判斷是否進(jìn)行入庫
        AddPoint addPoint = method.getAnnotation(AddPoint.class);
        if(addPoint.add()){
            System.out.println("入庫成功");
        } else {
            System.out.println("入庫失敗");
        }
    }


    /**
     * 異常通知 用于攔截記錄異常日志
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(pointcut = "aspect()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable e) {
        try {
            System.out.println("=====異常通知開始=====");
            System.out.println("異常代碼:" + e.getClass().getName());
            System.out.println("異常信息:" + e.getMessage());
            System.out.println("異常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()") + "." + operationType);
            System.out.println("方法描述:" + operationName);
            System.out.println("=====異常通知結(jié)束=====");
        } catch (Exception ex) {
            //記錄本地異常日志  
            logger.error("==異常通知異常==");
            logger.error("異常信息:{}", ex.getMessage());
        }
        /*==========記錄本地異常日志==========*/
        logger.error("異常方法:{}異常代碼:{}異常信息:{}參數(shù):{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage());

    }
}
/**
     * 這是調(diào)用者的業(yè)務(wù)模塊 這里讓線程休眠了5秒 為了判斷是調(diào)用者先執(zhí)行 還是切入點(diǎn)先執(zhí)行 
     * @throws InterruptedException
     */
    @AddPoint(add = true)
    public void addPoint() throws InterruptedException {
        Thread.sleep(5000);
        System.out.println("添加積分成功");
    }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容