[英]How do I prevent Spring Boot AOP from removing type annotations?
我对 Spring Boot 及其 AOP 风格很陌生,但对其他语言和 AOP 框架的编程并不陌生。 我不知道如何解决这一挑战。
我有一个简单的元数据装饰器:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GreetingsMeta {
public float version() default 0;
public String name() default "";
}
它适用于依赖注入:
public GreetingController(List<IGreetingService> greetings) throws Exception {
this.greetings = new HashMap<>();
greetings.forEach(m -> {
Class<?> clazz = m.getClass();
if (clazz.isAnnotationPresent(GreetingsMeta.class)) {
GreetingsMeta[] s = clazz.getAnnotationsByType(GreetingsMeta.class);
this.greetings.put(s[0].name(), m);
}
});
}
直到我应用了标准的日志记录方面:
@Aspect
@Component
public class LoggingAspect {
@Around("execution(* com.firm..*(..)))")
public Object profileAllMethods(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String methodName = methodSignature.getName();
final StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = joinPoint.proceed();
stopWatch.stop();
LogManager.getLogger(methodSignature.getDeclaringType())
.info(methodName + " " + (stopWatch.getTotalTimeSeconds() * 1000) + " µs");
return result;
}
}
然后 annotationsData 列表变为空,甚至 @Component 注释也不见了。
示例元装饰 class:
@Component
@GreetingsMeta(name = "Default", version = 1.0f)
public class DefaultGreetingsService implements IGreetingService {
@Override
public String message(String content) {
return "Hello, " + content;
}
}
我应该如何排除故障?
如何防止 Spring Boot AOP 删除类型注释?
Spring 引导不会删除任何内容,但对于 Spring,AOP 使用在运行时生成的动态代理,即带有事件挂钩(连接点)的子类或接口实现,用于通过切入点连接的方面建议代码。 默认情况下,注释不会被继承,因此这只是 JVM 功能。
子类从父类继承注解有一个例外:您可以将元注解@Inherited
添加到您自己的注解 class GreetingsMeta
中。 效果将是,如果您使用它注释任何 class,所有子类(也是由 Spring AOP 创建的动态代理)将继承该注释,并且您的原始代码应该按预期运行。
因此,在这种情况下,无需按照JC Carrillo的建议使用AnnotationUtils
。 当然,他的方法也有效。 它只是更复杂,因为AnnotationUtils
在内部使用了大量的反射魔法和大量的辅助类来计算结果。 因此,我只会在您不直接注释 class 而是例如方法或接口的情况下使用AnnotationUtils
,因为@Inherited
对它们没有影响,如文档所述。 或者,如果您依赖于 Spring(或自己的)元注释(注释上的注释)的层次结构,并且您需要将它们中的信息全部合并为一个,则AnnotationUtils
或MergedAnnotations
是合适的。
您可能想查看AnnotationUtils
Method method = methodSignature.getMethod();
GreetingsMeta greetingsMeta = AnnotationUtils.findAnnotation(method, GreetingsMeta.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.