无法在Spring中继承@Component? [英] Can't get @Component to be inherited in Spring?

查看:397
本文介绍了无法在Spring中继承@Component?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,有一个通用基类,所有客户端类都可以扩展.这有一个@Autowired字段,需要由Hibernate注入.这些都分组在另一个具有基类的@Autowired集合的类中.

In my project there's a common base class that all client classes extend. This has an @Autowired field that needs to be injected by Hibernate. These are all grouped together in another class that has an @Autowired collection of the base class.

为了减少客户端代码的样板,我正在尝试继承@Component.使用@Component默认情况下不执行此操作(显然

In order to reduce boilerplate for client code I'm trying to get @Component inherited. With @Component not doing this by default (apparently it used to though), I created this workaround annotation

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
public @interface InheritedComponent {
}

...并用它注释基类.它不漂亮,但我希望它能起作用.不幸的是没有,这确实让我感到困惑,因为@Inherited应该可以使它工作

... and annotated the base class with it. Its not pretty but I hoped it would work. Unfortunately it didn't, which really confuses me as @Inherited should make it work

还有其他方法可以继承@Component吗?还是我只说任何扩展基类的类都需要这个样板?

Is there any other way to get @Component inherited? Or do I just have to say that any class that extends the base class needs this boilerplate?

推荐答案

问题是Component注释类型本身需要用@Inherited标记.

The problem is that the Component annotation type itself needs to be marked with @Inherited.

您的@InheritedComponent注释类型可以由任何扩展了用@InheritedComponent标记的超类的类正确继承-但它不会继承@Component.这是因为您在注释上有@Component,而不是父类型.

Your @InheritedComponent annotation type is correctly inherited by any classes that extend a superclass which is marked with @InheritedComponent - but it does not inherit @Component. This is because you have @Component on the annotation, not the parent type.

一个例子:

public class InheritedAnnotationTest {

    @InheritedComponent
    public static class BaseComponent {
    }

    public static class SubClass extends BaseComponent {
    }

    public static void main(String[] args) {
        SubClass s = new SubClass();

        for (Annotation a : s.getClass().getAnnotations()) {
            System.out.printf("%s has annotation %s\n", s.getClass(), a);
        }
    }
}

输出:

class brown.annotations.InheritedAnnotationTest $ SubClass具有批注@ brown.annotations.InheritedComponent()

class brown.annotations.InheritedAnnotationTest$SubClass has annotation @brown.annotations.InheritedComponent()

换句话说,在解析类具有的注释时,不会解析注释的注释-它们不适用于类,仅适用于注释(如果有意义).

In other words, when resolving what annotations a class has, the annotations of the annotations are not resolved - they do not apply to the class, only the annotation (if that makes sense).

这篇关于无法在Spring中继承@Component?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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