java – 不能在Spring中继承@Component?

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

为了减少客户端代码的样板,我试图让@Component继承.由于@Component默认情况下不执行此操作(显然为it used to though),因此我创建了此变通方法注释

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

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

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

解决方法

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

您的@InheritedComponent注解类型由扩展超类的任何类正确继承,该类被标记为@InheritedComponent,但不会继承@Component.这是因为您在注释上具有@Component,而不是父类型.

一个例子:

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 has annotation @brown.annotations.InheritedComponent()

换句话说,当解析类具有什么注释时,注释的注释不会被解析 – 它们不适用于类,只适用于注释(如果有意义).

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。