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

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

1、切点方法
@RequestMapping("productSend")
@ProductSendLog
@StatisticalLogAnnotation
public Result<Object> 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);  
        }

    ...
    }

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值