Java Magazine, Nov/Dec 2017
ORACLE COM JAVAMAGAZINE NOVEMBER DECEMBER 2017 24 java ee 8 Simplified Programmatic Creation of Beans CDI has the well known concept of producers Simply put a producer is a kind of general factory method for some type Its defined by annotating a method with @ Produces An alternative factory for a type is simply a class itself a class is inherently a factory of objects of its own type In CDI both of these kinds of factories are represented by the Bean T type The name might be somewhat confusing but a Bean T in CDI is thus not a bean itself but a type used to create instances that is a factory An interesting aspect of CDI is that those Bean T instances are not just internally created by CDI after encountering class definitions and producer methods they can be added programmatically by user code as well Via this mechanism its possible to dynamically register these factories This ability can be handy in a variety of cases for instance when many similar producer methods would have to be defined statically or when generic producers are needed As it stands generics are not particularly well supported In CDI 20 you can take advantage of the new InterceptionFactory to bind a libraryshipped interceptor to a library shipped built in bean in CDI Instead of trying to create a somewhat generic producer an alternative strategy could be to actually scan which types an application is using and then dynamically create a Bean T for each type Programmatically adding a Bean T instance and using CDI producers are techniques that overlap somewhat in functionality The diference is that CDI producers essentially make only the create instance aspect dynamic the rest such as scope types and so on is more or less static However a programmatically added Bean T makes all those aspects dynamic The downside of a Bean T is that it has to be added via a CDI extension which runs only when CDI starts up In CDI 1 x programmatically adding Bean T is quite a bit of work and a bit complex because it requires you to decide what to return as a default for various methods that are not directly of interest
You must have JavaScript enabled to view digital editions.