在Spring代理bean中查找注释

Leo*_*nel 14 spring

我已经为类创建了自己的注释:@MyAnnotation并且用它注释了两个类.

我还在Spring的这些类中注释了一些方法@Transactional.根据事务管理Spring文档,bean工厂实际上将我的类包装到代理中.

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

  1. 方法getBeansWithAnnotation正确返回我声明的bean.好.
  2. bean的类实际上是Spring生成的代理类.好的,这意味着该@Transactional属性被找到并且有效.
  3. 方法findAnnotation 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实例的最终目标类,不仅遍历顶级代理,还遍历任意数量的嵌套代理 - 尽可能长时间没有副作用,即仅针对单例目标.


Leo*_*nel 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 !
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何找到具有给定注释的*方法*? (8认同)