【问题标题】:getAnnotation returns null for methods in different maven modulegetAnnotation 为不同 maven 模块中的方法返回 null
【发布时间】:2017-03-15 18:57:46
【问题描述】:

我在 maven 模块“A”中创建了下面的注释

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CacheDelete {...}

在同一个模块“A”中,我有 TestPojo 类,我正在使用这个注解

@CacheDelete()
public void removeTestPojo(int id) {

}

我从模块“A”的测试用例中调用了这个 removeTestPojo() 方法。这里一切正常。我在我的建议中使用以下代码获得了正确的注释。

模块“A”中的建议方法代码CacheAspect类:

CacheDelete cacheDeleteAnnotation = getAnnotation((MethodSignature) joinPoint.getSignature(),
      CacheDelete.class);

获取注解方法:

private <T extends Annotation> T getAnnotation(MethodSignature methodSignature,
  Class<T> annotationClass) {
     return methodSignature.getMethod().getAnnotation(annotationClass);
}

问题: 现在我有一个不同的模块“B”,我在其中使用“A”的依赖项,并且“B”模块中的一个方法用@CacheDelete 注释。

当我在模块“B”中为带注释的方法运行测试用例并调试 CacheAspect 类时,我的建议是调试点,但我的 get 注释在这里返回 null。 谁知道是什么原因?

【问题讨论】:

  • 虽然这看起来很复杂,但我认为你应该提出一个minimal reproducible example。否则我们无能为力。
  • 对我来说会有点复杂。我自己在这里工作是为了弄清楚:)

标签: java annotations aop


【解决方案1】:

得到了它与不同模块无关的问题。我注释了作为接口实现的方法,并通过接口引用变量调用实现的方法。

所以当你使用时:

(MethodSignature) proceedingJoinPoint.getSignature().getMethod() 

从接口返回方法;

我将上面的代码替换为:

MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
String methodName = method.getName();
if (method.getDeclaringClass().isInterface()) {
  method = proceedingJoinPoint.getTarget().getClass().getDeclaredMethod(methodName,
      method.getParameterTypes());
}

所以,这将检查方法是否为接口,如果是,我将调用:

proceedingJoinPoint.getTarget().getClass().getDeclaredMethod()

这给了我子类的方法。

奇怪的是,当我们通过接口调用子类方法时,当注解在子类方法中使用时,调用传播到advice(AOP),而注解在子类方法中没有传播。

【讨论】:

  • 很高兴您解决了自己的问题,但下次先考虑如何重现问题,然后再提出问题。我认为您绝对没有理由不能提供所要求的MCVE @GhostCat。这是 StackOverflow,不是测验。我想我之前告诉过你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2020-01-21
相关资源
最近更新 更多