在Spring代理Bean中查找注释 [英] Find annotation in Spring proxy bean

查看:176
本文介绍了在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.

  1. 方法getBeansWithAnnotation正确返回我声明的bean. 好.
  2. bean的类实际上是Spring生成的代理类. ,这意味着@Transactional属性已找到并起作用.
  3. 方法findAnnotation在Bean中找不到MyAnnotation. .我希望我可以从实际的类或代理中无缝读取此注释.
  1. Method getBeansWithAnnotation correctly returns my declared beans. Good.
  2. The class of the bean is actually a proxy class generated by Spring. Good, this means the @Transactional attribute is found and works.
  3. 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 !
  //
}

推荐答案

您可以通过调用

确定 给定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代理Bean中查找注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆