© Luqman Saeed 2020Luqman SaeedIntroducing Jakarta EE CDIhttps://doi.org/10.1007/978-1-4842-5642-8_9
9. CDI Stereotypes
CDI stereotypes are an API construct that help you group together similar architectural patterns into one annotation. In the restaurant application you learned about in Chapter 8, there is a class named QueryService that you need to transform into a transactional, logged, request scoped bean to carry out a query service in the data layer.
Now assume this requirement will apply to other beans as well. What this means is that QueryService would look like the following.
Lines 1-3 use the @RequestScoped, @Transactional, and @Logging annotations to declare the QueryService bean. The @Transactional annotation is an interceptor from the Java Transaction API. @Loggin is the logging interceptor. If the application grows and there is a need for more service layer classes, every single one of those classes is going to have to repeat these annotations.
Using CDI stereotypes, you can group these commonly required annotations into one annotation so that using that single stereotype will result in the activation of all the other annotations. You can declare a CDIService stereotype to use on the QueryService class as follows.
This code snippet declares a stereotype called CDIService using the @Stereotype annotation on Line 1. Line 2 then declares this stereotype as having a request scope. Line 3 declares CDIService as being @Transactional, meaning that every method in a class annotated with @CDIService will be run as a transaction. Line 4 declares @Logging, making @CDIService loggable. Line 5 then uses the CDI qualifier called @Named to make any @CDIService annotated class available to any JSF page. Line 6 declares the retention as RUNTIME and Line 7 declares the target as TYPE, meaning that @CDIService can only be used on classes.
Now you can apply this newly created stereotype to the QueryService bean to make it instantly a request-scoped, transactional, loggable, named bean.
Line 1 in this code snippet shows the use of the @CDIService stereotype on the QueryService. So with that, you have replaced the need for (and the tedious repetition of) four annotations with just one.
This is how you can use CDI stereotypes to simplify and compact your code. If you need to make your data layer service classes application instead of request scope, all you have to do is change the scope at the stereotype definition level and that will instantly be available on all @CDIService annotated beans.