我已经为类创建了自己的注释:@MyAnnotation并且用它注释了两个类.
我还在Spring的这些类中注释了一些方法@Transactional.根据事务管理的Spring文档,bean工厂实际上将我的类包装到代理中.
最后,我使用以下代码来检索带注释的bean.
getBeansWithAnnotation正确返回我声明的bean.好.@Transactional属性被找到并且有效.MyAnnotation在bean中找不到.坏.我希望我可以无缝地从实际的类或代理中读取这个注释.如果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 !
//
}
Run Code Online (Sandbox Code Playgroud)
dna*_*ult 11
您可以通过调用AopProxyUtils.ultimateTargetClass找到代理bean的真实类.
确定给定bean实例的最终目标类,不仅遍历顶级代理,还遍历任意数量的嵌套代理 - 尽可能长时间没有副作用,即仅针对单例目标.
解决方案不是对bean本身起作用,而是要求应用程序上下文.
使用方法ApplicationContext#findAnnotationOnBean(String,Class).
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 !
*/
MyAnnotation annotation = ctx.findAnnotationOnBean(beanName, MyAnnotation.class);
// Yay ! Correct !
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10857 次 |
| 最近记录: |