【发布时间】:2011-09-09 13:39:37
【问题描述】:
我为类创建了自己的注释:@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 !
//
}
【问题讨论】:
-
它是什么样的代理? (JDK 与 cglib 等)。
-
我猜 Spring 默认使用 JDK 代理。
-
似乎这将是对框架的一个很好的增强。自从您很久以前发帖以来,您是否对此进行过调查?
标签: spring