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