カスタム注釈とAOPの組み合わせ

2764 ワード

まず業務について述べると,各モジュールである要求に達すると現在のユーザにポイントを追加するので,ここでは注釈コーディネート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("      ");
    }