首先叙述一下业务,在每个模块中达到某要求时都要给当前用户添加积分,所以这里用到了注解搭配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);
//切入点是自定义注解类的地址
@Pointcut("@annotation(org.cqbanxi.smartcity.common.biz.anno.AddPoint)")
public void aspect() {
}
@Around("aspect()")
public void addPoint(ProceedingJoinPoint point) throws Throwable {
//执行调用者类中的方法
point.proceed();
Signature signature = point.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
//获取注解中的属性 判断是否进行入库
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("=====异常通知结束=====");
} catch (Exception ex) {
//记录本地异常日志
logger.error("==异常通知异常==");
logger.error("异常信息:{}", ex.getMessage());
}
/*==========记录本地异常日志==========*/
logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage());
}
}
/**
* 这是调用者的业务模块 这里让线程休眠了5秒 为了判断是调用者先执行 还是切入点先执行
* @throws InterruptedException
*/
@AddPoint(add = true)
public void addPoint() throws InterruptedException {
Thread.sleep(5000);
System.out.println("添加积分成功");
}