我在 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。 有人知道这可能是什么原因吗?
最佳答案
遇到问题,它与不同的模块无关。我注释了作为接口(interface)实现的方法,并通过接口(interface)引用变量调用实现的方法。
所以当你使用时:
(MethodSignature) proceedingJoinPoint.getSignature().getMethod()
它从接口(interface)返回方法;
我将上面的代码替换为:
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());
}
因此,这将检查方法是否是接口(interface),如果是,我将调用:
proceedingJoinPoint.getTarget().getClass().getDeclaredMethod()
这给了我子类的方法。
奇怪的是,当我们通过接口(interface)调用子类方法时,当子类方法中使用注释时,调用会传播到通知(AOP),但注释不会在子类方法中传播。
关于java - getAnnotation 对于不同 Maven 模块中的方法返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42804147/