入坑:多个自定义注解添加到同一方法中

1、切点方法

@RequestMapping("productSend")
@ProductSendLog
@StatisticalLogAnnotation
public Result productSend() {
......
}

2、自定义注解@ProductSendLog

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface ProductSendLog {

    String operation();
}

3、自定义注解@StatisticalLogAnnotation

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface StatisticalLogAnnotation {
...
}

4、Aop切面ProductSendLogAspect

@Component
@Aspect
@Slf4j
public class ProductSendLogAspect {
    @Resource
    private RedisDaoImpl redisDao;

    @Pointcut("@annotation(com.xkd.common.annotation.ProductSendLog)")
    public void aspect() {

    }
    
    @AfterReturning(value="@annotation(annotation)", returning = "obj")
    public void doAfter(JoinPoint joinPoint, ProductSendLog annotation, Object obj){
    ...
    }

5、Aop切面StatisticalLogAspect

@Component
@Aspect
@Slf4j
public class StatisticalLogAspect {
    @Resource
    private RedisDaoImpl redisDao;

    @Pointcut("@annotation(com.xkd.common.annotation.StatisticalLogAnnotation)")
    public void aspect() {

    }
    
    @AfterReturning(value="@annotation(annotation)", returning = "obj")
    public void doAfter(JoinPoint joinPoint, StatisticalLogAnnotation annotation, Object obj){
    ...
    }

以上情况,同一个接口添加了两个自定义注解,并且两个自定义注解所执行的aop的自定义注解对象都是通过@annotation()方式引入的。 将会导致两个自定义注解一起注入到参数的自定义注解类中。

例如:StatisticalLogAspect类中的doAfter方法的参数StatisticalLogAnnotation 在依赖注入的时候,会注入StatisticalLogAnnotation对象和ProductSendLog对象。导致参数类型不匹配问题。


解决方案:

将其中一个切面地注入自定义注解类的方式修改成其他形式。
例如:

@Component
@Aspect
@Slf4j
public class ProductSendLogAspect {
    @Resource
    private RedisDaoImpl redisDao;

    @Pointcut("@annotation(com.xkd.common.annotation.ProductSendLog)")
    public void aspect() {

    }

    @AfterReturning(value = "aspect()", returning = "obj")
    public void doAfter(JoinPoint joinPoint, Object obj){
      MethodSignature signature = null;
      if (joinPoint.getSignature() instanceof MethodSignature) {
            signature = (MethodSignature) joinPoint.getSignature();
        }
      if (signature != null) {
          Method method = signature.getMethod();
          ProductSendLog annotation = method.getAnnotation(ProductSendLog.class);  
        }

    ...
    }

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章