我为类创建了自己的注释:@MyAnnotation
,并用它注释了两个类。
我还用 Spring 的 @Transactional
注释了这些类中的一些方法。根据Spring documentation for Transaction Management , bean factory 实际上将我的类包装成一个代理。
最后,我使用以下代码来检索带注释的 bean。
- 方法
getBeansWithAnnotation
正确返回我声明的 bean。 很好。 - bean的类实际上是Spring生成的代理类。 很好,这意味着
@Transactional
属性已找到并且有效。 - 方法 findAnnotation 没有在 bean 中找到
MyAnnotation
。 不好。我希望我能从实际的类或代理中无缝地读取此注释。
如果 bean 是代理,我如何找到实际类上的注解?
我应该使用什么来代替 AnnotationUtils.findAnnotation()
以获得所需的结果?
Map<String,Object> beans = ctx.getBeansWithAnnotation(MyAnnotation.class);
System.out.println(beans.size());
// prints 2. ok !
for (Object bean: services.values()) {
System.out.println(bean.getClass());
// $Proxy
MyAnnotation annotation = AnnotationUtils.findAnnotation(svc.getClass(), MyAnnotation.class);
//
// Problem ! annotation is null !
//
}
最佳答案
您可以通过调用AopProxyUtils.ultimateTargetClass 找到代理bean 的真实类。 .
Determine the ultimate target class of the given bean instance, traversing not only a top-level proxy but any number of nested proxies as well - as long as possible without side effects, that is, just for singleton targets.
关于spring - 在 Spring 代理 bean 中查找注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6257092/