无法让@Component在Spring中inheritance?
在我的项目中,有一个所有客户端类都扩展的公共基类。 这有一个@Autowired字段,需要由Hibernate注入。 这些都在另一个具有@Autowired基类集合的类中组合在一起。
为了减少客户端代码的样板,我试图让@Componentinheritance。 由于@Component默认情况下没有这样做(显然它曾经用过 ),我创建了这个变通办法注释
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Component @Inherited public @interface InheritedComponent { }
…并用它注释基类。 它不漂亮,但我希望它会起作用。 不幸的是它没有,这真让我感到困惑,因为@Inherited应该让它发挥作用
还有其他方法可以inheritance@Component吗? 或者我只是要说任何扩展基类的类都需要这个样板?
问题是Component
注释类型本身需要用@Inherited
标记。
@InheritedComponent
注释类型由任何扩展超类的类正确inheritance,该类使用@InheritedComponent
标记 – 但它不inheritance@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有注释@ brown.annotations.InheritedComponent()
换句话说,当解析类具有的注释时,注释的注释不会被解析 – 它们不适用于类,只适用于注释(如果有意义)。
我通过创建自己的注释(heritable)然后自定义类路径扫描来处理这个问题:
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Component @Inherited public @interface BusinessService { }
Spring配置看起来像这样:
来自Spring doc 5.10.3使用filter来自定义扫描