首先敘述一下業(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("添加積分成功");
}