无法在Spring中继承@Component? [英] Can't get @Component to be inherited in Spring?
问题描述
在我的项目中有一个所有客户端类都扩展的公共基类.这有一个需要由 Hibernate 注入的 @Autowired 字段.这些都在另一个类中组合在一起,该类具有基类的 @Autowired 集合.
为了减少客户端代码的样板,我试图继承@Component.@Component 默认不这样做(显然 它曾经使用过),我创建了这个解决方法注释
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@成分@遗传公共@interface InheritedComponent {}
... 并用它注释基类.它不漂亮,但我希望它会起作用.不幸的是它没有,这真的让我感到困惑,因为@Inherited 应该让它工作
还有其他方法可以继承@Component吗?或者我必须说任何扩展基类的类都需要这个样板?
问题是Component
注解类型本身需要用@Inherited
标记.>
您的 @InheritedComponent
注释类型被任何扩展超类的类正确继承,该超类标记为 @InheritedComponent
- 但它不继承 @Component代码>.这是因为您在 注释 上有
@Component
,而不是父类型.
示例:
公共类 InheritedAnnotationTest {@继承组件公共静态类 BaseComponent {}public static class SubClass extends BaseComponent {}公共静态无效主(字符串 [] args){子类 s = 新子类();for (注解 a : s.getClass().getAnnotations()) {System.out.printf("%s 有注释 %s\n", s.getClass(), a);}}}
输出:
<块引用>class brown.annotations.InheritedAnnotationTest$SubClass 有注解@brown.annotations.InheritedComponent()
换句话说,当解析一个类有哪些注解时,注解的注解不会被解析——它们不适用于类,只应用于注解(如果有意义的话).
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.
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 {
}
... 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
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?
The problem is that the Component
annotation type itself needs to be marked with @Inherited
.
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.
An example:
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);
}
}
}
Output:
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屋!