Can't get @Component to be inherited in Spring?

后端 未结 2 1576
谎友^
谎友^ 2021-02-04 09:51

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

相关标签:
2条回答
  • 2021-02-04 10:29

    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).

    0 讨论(0)
  • 2021-02-04 10:34

    I've dealt with this issue by creating my own annotation (heritable) and then customizing classpath scanning:

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

    Spring configuration look likes this:

    <context:component-scan base-package="io.bar">
            <context:include-filter type="annotation"
                expression="io.bar.core.annotations.BusinessService" />
        </context:component-scan>
    

    from Spring doc 5.10.3 Using filters to customize scanning

    0 讨论(0)
提交回复
热议问题