spring - 在 Spring 代理 bean 中查找注解

标签 spring

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

我还用 Spring 的 @Transactional 注释了这些类中的一些方法。根据Spring documentation for Transaction Management , bean factory 实际上将我的类包装成一个代理。

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

  1. 方法 getBeansWithAnnotation 正确返回我声明的 bean。 很好。
  2. bean的类实际上是Spring生成的代理类。 很好,这意味着 @Transactional 属性已找到并且有效。
  3. 方法 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 !
  //
}

最佳答案

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

Determine the ultimate target class of the given bean instance, traversing not only a top-level proxy but any number of nested proxies as well - as long as possible without side effects, that is, just for singleton targets.

关于spring - 在 Spring 代理 bean 中查找注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6257092/

相关文章:

java - Spring @RestController 注释,带有来自 beans.xml 的根上下文

java - 使用 Spring Security 取消 Spring 流的安全

java.lang.NoClassDefFoundError :-Could not initialize class org. apache.http.impl.conn.ManagedHttpClientConnectionFactory

java - 在 Eclipse 中创建类似于 Spring Petclinic 的项目结构

java - 什么是分组通量以及我们如何使用分组通量?

java - 如何使用 Spring 和 JPA 设置多个数据源

java - 运行 mvn clean install 应用程序尝试将 postgres 连接到错误的端口

java - 如何将表单元素映射到两个pojo对象

java - JRebel 6.4.6 插件在 IDEA 16 和 Tomcat 9 中不起作用

java - Spring MVC 覆盖接收到的内容类型