CDI has a very nice feature that is not used as often as it should be: Stereotypes. They allow you to group a set of annotations into a single, more abstract, and hopefully more descriptive annotation; e.g. the built-in @Model
stereotype defines that the annotated class defines a model in an MVC architecture. For more details and examples, see the javadoc.
Stereotypes only work within CDI — annotations from other standards, can’t be stereotyped; so you always have to carefully make sure that you use only CDI annotations. E.g., you can’t define a @Boundary
annotation for your JAX-RS service interface classes that provides a @Stateless
annotation:
@Stereotype
@Retention(RUNTIME)
@Stateless
public @interface Boundary {}
There won’t be any errors, it just won’t work. This makes the use of stereotypes error prone; so many prefer to never use them at all.
This reduced applicability makes it hard to keep it as a valid option in mind.
s@p
(like in 'the sap is rising') is an annotation processor that does the resolution of annotations at compile time. In this way, the resolution also works for libraries that don’t support stereotypes out-of-the-box. I.e. the example from above would just work after putting s@p
on the classpath while compiling! A demo test.war
doing exactly this can be found in the test
module.
The implementation works by manipulating the javac
AST; similar to how Lombok works.
This is currently just a proof-of-concept, waiting for your feedback on how it can improve. When doesn’t it work correctly? What features are missing? Spring has some very helpful and well-tested features to learn from! Should we automatically propagate annotations from class to method/field? Or from package to classes? How can IDEs recognise the resolution? Should we use our own Stereotype annotation instead? Maybe @Metatype
? Some features may be framework specific; should we bake them in? Or make it all configurable? Or allow plugins? What priorities do these things have? How big is the overall demand and potential? Would it make sense to get this into a standard like Microprofile?
A more solid approach would be to have all standards requiring support for Stereotypes. That’s a lot of standards to be changed. The main concern that committees for standards like JAX-RS will probably raise, is the added dependency on CDI. It would be technically possible to define that dependency to be optional: only if Stereotype
is on the classpath, it has to be considered. But it’s still a lot of work to convince everybody, and even if most standards would follow, even a single standard not following would mean inconsistency; and thereby greatly reduce the usefulness.
Maybe s@p
can be a step into that direction.