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

前端之家收集整理的这篇文章主要介绍了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?或者我只需要说扩展基类的任何类都需要这个样板?

@H_404_10@

解决方法

问题是组件注释类型本身需要用@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()

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

@H_404_10@ @H_404_10@ 原文链接:https://www.f2er.com/java/125920.html

猜你在找的Java相关文章