相关疑难解决方法(0)

在Spring代理bean中查找注释

我已经为类创建了自己的注释:@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)

spring

14
推荐指数
2
解决办法
1万
查看次数

带有自定义注释的 Spring bean

我已经用自定义注释注释了 Spring bean,但似乎 Spring 在创建 bean 后删除了我的自定义注释。

AnnotatedBean bean = ctx.getBean(AnnotatedBean.class);

Foo.findAndDoStuffWithAnnotatedThings(bean);
Run Code Online (Sandbox Code Playgroud)

第二步不起作用,我的自定义注释丢失了。(可能是由于代理的东西)

我的豆子

@Rule(name = "RoutePickupRule")
@Transactional
@Component
public class AnnotatedBean{


    @Autowired
    private ICarpoolDoa carpoolDAO;

    @Condition
    public boolean condition(CustomLocation customLocation, String userId) {
        //snip
    }

    @Action
    public void action() {
        //snip
    }  
Run Code Online (Sandbox Code Playgroud)

我的自定义注释之一的示例

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Condition {

}
Run Code Online (Sandbox Code Playgroud)

findAndDoStuffWithAnnotatedThings Bean中的错误
被传递到验证我的自定义注释的类,但我的验证程序找不到任何注释。(Util 使用isAnnotationPresent方法)。同样,当我使用“new”自己创建 bean 时,没有问题。

public class RuleAnnotationVerifier {


    public void RuleAnnotationVerifier(final Object rule) {
        checkRuleClass(rule);
        checkConditionMethod(rule);
        checkActionMethod(rule);
    }

    private void checkRuleClass(final Object rule) {
        if …
Run Code Online (Sandbox Code Playgroud)

spring annotations spring-bean

1
推荐指数
1
解决办法
4886
查看次数

标签 统计

spring ×2

annotations ×1

spring-bean ×1