Java – can’t inherit @ component in spring?
In my project, there is a common base class, and all client classes are extended There is an @ Autowired field, which needs to be injected by hibernate These are grouped in another class that has the @ Autowired collection of the base class
In order to reduce the template of client code, I try to make @ component inherit Since @ component does not do this by default (obviously it used to though), I created this workaround annotation
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Component @Inherited public @interface InheritedComponent { }
... and annotate the base class with it It's not beautiful, but I hope it will work Unfortunately not, it really puzzles me because @ inherited should make it work
Is there any other way to inherit @ component? Or do I just need to say that any class that extends the base class needs this template?
Solution
The problem is that the Component annotation type itself needs to be marked with @ inherited
Your @ inheritedcomponent annotation type is correctly inherited by any class that extends the superclass, which is marked as @ inheritedcomponent, but 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:
In other words, when a class has any annotations, the annotations of the annotations are not resolved – they do not apply to the class, only to the annotations (if meaningful)