在Spring代理bean中查找注释

时间:2011-06-06 19:39:53

标签: spring

我为类创建了自己的注释:@MyAnnotation,并用它注释了两个类。

我还在Spring的@Transactional这些类中注释了一些方法。根据{{​​3}},bean工厂实际上将我的类包装成代理。

最后,我使用以下代码检索带注释的bean。

  1. 方法getBeansWithAnnotation正确返回我声明的bean。 好。
  2. bean的类实际上是Spring生成的代理类。 ,这意味着@Transactional属性已找到且有效。
  3. 方法findAnnotation在bean中找不到MyAnnotation。我希望我可以无缝地从实际的类或代理中读取这个注释。
  4. 如果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 !
      //
    }
    

2 个答案:

答案 0 :(得分:10)

您可以通过调用AopProxyUtils.ultimateTargetClass找到代理bean的真实类。

  

确定   给定bean实例的最终目标类,不遍历   只有一个顶级代理,但任何数量的嵌套代理也是如此   尽可能长的没有副作用,也就是说,只为单身人士   目标

答案 1 :(得分:8)

解决方案不是处理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 !
}
相关问题