在Spring代理Bean中查找注释 [英] Find annotation in Spring proxy bean
本文介绍了在Spring代理Bean中查找注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为类@MyAnnotation
创建了自己的注释,并为其注释了两个类.
I have created my own annotation for classes: @MyAnnotation
, and have annotated two classes with it.
我还用Spring的@Transactional
注释了这些类中的一些方法.根据对于事务管理的春季文档,bean工厂实际上将我的类包装到了代理中.
I have also annotated a few methods in these classes with Spring's @Transactional
. According to the Spring documentation for Transaction Management, the bean factory actually wraps my class into a proxy.
最后,我使用以下代码来检索带注释的bean.
Last, I use the following code to retrieve the annotated beans.
- 方法
getBeansWithAnnotation
正确返回我声明的bean. 好. - bean的类实际上是Spring生成的代理类. 好,这意味着
@Transactional
属性已找到并起作用. - 方法findAnnotation在Bean中找不到
MyAnnotation
. 坏.我希望我可以从实际的类或代理中无缝读取此注释.
- Method
getBeansWithAnnotation
correctly returns my declared beans. Good. - The class of the bean is actually a proxy class generated by Spring. Good, this means the
@Transactional
attribute is found and works. - Method findAnnotation does not find
MyAnnotation
in the bean. Bad. I wish I could read this annotation from the actual classes or proxies seamlessly.
如果bean是代理,我如何在实际的类上找到注释?
If a bean is a proxy, how can I find the annotations on the actual class ?
我应该使用什么代替AnnotationUtils.findAnnotation()
以获得期望的结果?
What should I be using instead of AnnotationUtils.findAnnotation()
for the desired result ?
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 !
//
}
推荐答案
查看全文