Forcing derived classes to declare themselves as Spring bean

65 Views Asked by At

How can I control, that all classes, that derive from a certain class, have to be declared as @Component (that means as a Spring bean)? Is Spring offering a mechanism for controling this via the parent class?

1

There are 1 best solutions below

1
On

Workarround: you could use [AspectJ to declare warnings][1] (or errors) if the subclass of your parent class does not have a @Component annotation.

(I am not an AspectJ expert, so I can not write you the needed AJP declaration. But I have done something similar some years ago, so I am pretty sure that this approach works.)

rough sketch, contains maybe some syntax errors:

pointcut requiresComponentAnnotation(): yourParentClass+ 
         && !get(@Component)
declare warning : requiresComponentAnnotation() : 
        "expect: @Type(type = \"org.springframework.stereotyp.Component\")";