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
Componentannotation type itself needs to be marked with@Inherited.Your
@InheritedComponentannotation 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@Componenton the annotation, not the parent type.An example:
Output:
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).