Sunday, September 14, 2014

Integrating Configuration with CDI 2.0

Integrating Configuration with CDI

Most of you are aware that the original initiative of standardizing of configuration for Java EE deployment aspects was stopped lately. But looking at the topic of configuration we have multiple aspects:

  1. Deployment configuration in Java EE configuring a deployment into a Java EE server, including things like configuration of EJBs, transactions, datasources, servlets and filters etc. You can basically see this part as a replacement or improvement over the scattered file configurations as of today (web.xml, ejb.jar.xml, ...).
  2. Configuration of aspects that basically are not related to the Java EE platform, but related to the use cases and logic implemented. We call it application configuration. Since dependencies from a configuration mechanism should be minimized, IMO inversion of control is my preferred design concept to be used to "configure" a component, so CDI is the one that matches best.
  3. If we leave Java EE and imagine our solution built up on Spring, JavaFX, OSGI or other technologies, configuration gets even more generic. In many cases, though the existence of JSR 330, we can not rely on IoC/Dependency Injection to be present, so we need also to provide some kind of SE API, e.g. as outlined in previous blogs here.
Now given the current situation, I suggest point 1 is not in scope anymore for Java EE 8. Nevertheless there is still much we can do:
  • Leverage CDI so it is configuration aware
  • Standardize configuration as a global and unified concept in a SE JSR.
In this blog I would like to focus on what would be possible extensions to CDI to support application configuration effectively. 

Usage Perspective: Injecting Configured Values

As a starting point lets just inject String properties, e.g. as follows

public class MyBean {

  private String myProperty;


This is the simplest case, it will request for a configuration entry, with the same name as the field, so it looks for "myProperty". Now in many cases we probably want to have a different configuration key to be used for the lookup:

 private String myProperty;

Now what should happen, if configuration is not present? I suggest, without any default value, it should be managed like a deployment error. So we also want to be able to pass a default value here:

 private String myProperty;

Obviously the configured value above is a number. So I would expect the runtime system is capable of injecting it also as number:

 private int myProperty;

Fine so far. Looking at Spring and other frameworks, you may also want to configure more complex things, e.g. injecting a Collection type:

 private List<String> MyList;

Since configuration is basically data added to a system externally it must also  be validatable, so we could add bean validation annotations on it:

 private int myProperty;

Basically looking at the code above it looks quite the same as what you can do with CDI already as of now. This makes sens since basically you simply do nothing different than injecting values. Similarly you want to separate different configurations in a system, may by qualifying them:

 @SystemConfig // Qualifier annotation
 private int myProperty

Finally default values also could support EL expressions:

 private Stage stage

Advanced Use Cases

Multiple Configuration Keys
In some cases there is a need to read out information from several configuration locations, hereby defining an order of precedence between several keys. That can be easily achieved by allowing an array of configuration keys to be defined within the annotation:

 public class MyBean {
  @Configured("myProperty", my.myconfig.myProperty")
  private int myProperty

Configuration Root Keys
When organizing configuration in a hierarchical tree, a component typically reads several keys out of one sub-path, often called configuration area. Instead of having to retype the area all the time (which is error prone), it can be added as a default on class level, so the following example would lookup configuration with keys a.b.c.myProperty, a.b.c.num:

 public class MyBean {
  private int myProperty;
  private int myProperty2;

Configuration Filtering
Similarly you want to add sometimes a filter (operator) converting the configured String value to another String value (e.g. decrypting an encrypted password):

 private String password;

Custom Adapter
Or you want to override/provide the converter to be used for type conversion from String to the required target type:

 private MonetaryAmount amount;

Listening to Configuration Changes
Several times we want to be aware if configuration values change. Basically we could simply listen for PropertyChangeEvent instances: 

public class MyBean {

  private String myProperty;

   * Event sent, whenever a configured property is
   * changed (reinjected).
   * @param evt the event describing the changed property
  void configChanged(@ConfigChange PropertyChangeEvent evt){

This would allow to get informed on configuration changes easily, but would not imply any internal know how, how configuration is managed.

Alternate: Constraint Injected Types to simple Type only

The above though clearly separated has a couple of intersection with CDI. So it might be an option to reduce the configurable types to only the following:
  1. All primitive types such as boolean, byte, char, short, int, long, float, double.
  2. The corresponding wrapper types such as Boolean, Character, Byte, Short, Integer, Long, Float, Double, but also Number.
  3. Additionally: String, BigDecimal, BigInteger.
This would result in a fairly simple configuration mechanism. Additional features can then be added on top of that using CDI mechanisms, e.g. factory or producer classes that provide corresponding more complex instances that can be injected in other places:

 public class NameListProvider{
   private String configuredList;

   @Produces @NamedList @Dependent
   public List<String> getNamedList(){
      List<String> result = new ArrayList<>();
      return result;
   private void parseList(List<String> list){ ... }

A possible disadvantage of this solution is that the conversions are not inherently reusable and therefore similar conversions may be duplicated multiple times on a system. 

CDI Perspective: How can configuration features be realized

Basic Mechanism

As a starting point let us elaborate the runtime requirements configured beans/properties should have. I would suggest something like the following:
  1. Configured properties are based on String values only and managed by the configuration system only and not related to CDI.
  2. They can be converted to any non String based type, but conversion will be performed by the configuration subsystem. Especially configured objects do not support injection of any dependencies.
  3. Configured properties can be qualified. 
  4. Configured values are injected during the initialization of the CDI bean. It is the responsibility of the configuration system to determine the correct value, e.g. depenending on the current runtime context, or whatever is required to determine the correct configured value. The CDI container only provides the glue mechanism so configuration can be injected at the right locations.
  5. Any configured values are always injected with @Dependent scope. Adding any other scope annotation is handled as a deployment error.

Realization Variants

When we look at the possible implementation requirements and the possible way, how this can be implemented using CDI, there are different possible options, how concerns can be separated between CDI and a configuration subsystem:

Extending CDI
In this scenario CDI would be extended. meaning, that CDI itself defines the required annotations such as @Configured, @ConfigChange and also provides an SPI interface that can be registered (e.g. with java.util.ServiceLoader) for accessing configuration values. One important key aspect is that CDI should not know how configuration is managed. Basically configuration can be as simple as a .properties file in the classpath. In other cases it may be multilayered, dynamic system that even may run external to the current VM. So we need some very general abstraction to decouple CDI from this complexities. A minimalistic variant of such an SPI interface could look as follows:

 public interface ConfigAccessor{
   <T> T getConfiguredValue(Field f, Object instance,
                            Class<T> type,
                            Annotation... qualifiers,

                            ConfigChangeListener l);
   void addConfigChangeListener(ConfigChangeListener l);
   void removeConfigChangeListener(ConfigChangeListener l);
Nevertheless this variant would have significant drawbacks:
  • It is questionable, if such an SPI should really be part of CDI.
  • Also CDI would probably not bring a configuration implementation with it (or only a very minimalistic one). 
An advantage of doing so, would be that the basic mapping between configuration and the CDI injection mechanisms is well defined. Nevertheless let's further see if we have other options.

Generalizing Producers
Looking at the examples we could also think about if the mechanisms shown could be generalized. Basically configuration injection is similar to satisfying dependencies using an external bean provider. Basically this what producers are built for. So basically we could also let CDI to the injection work...

 public class MyBean {

  @Inject @Configured
  private String myProperty;

...and add an according producer bean for injecting configuration and hereby defining @Configured as CDI qualifier:

 public class ConfigProducer{
   @Produces @Configured @Dependent
   public String getStringConfig(){...}
   @Produces @Configured @Dependent
   public Integer getStringConfig(){...}
   @Produces @Configured @Dependent
   public Boolean getStringConfig(){...}
Nevertheless, if we could define that a producer will provide instances for any kind of injection targets with a certain qualifier, this would definitively allow us to inject all kind of configured values. To achieve this I added an additional flag (ProducerType) to the @Produces annotation to tell the CDI container that this producer should be used to delegate object production to any kind of target types qualified with @Configured :

 public class ConfigProducer{

   @Produces(ProducerType.ALL@Configured @Dependent
   public Object getConfiguredValue(InjectionTarget<?> tgt){...}

Clearly also this variant has drawbacks: 

  • It is not type-safe.
  • Producers may easily have intersections with other producers and more easily lead to deployment errors.

Using Portable Extensions
Finally simply implementing a portable extension is not only enough, it provides also the most portable and powerful mechanism. Even the current CDI 1.1 is fully sufficient to implement a configuration feature seamlessly:
  • The extension listens to the ProcessInjectionTarget event. This will be called for every bean.
  • The extension could then check for @Configured (or @ConfigChange) annotations and could adapt the InjectionTarget, so it can intercept the injection process, when the bean is initalized. This allows to populate the bean created with the configuration values as needed (as dependent scope).
  • Similarly the extension manages the injected beans (using weak references), which want to listen for configuration changes. Similarly if the underlying configuration changes, it can reinject the according properties and call according methods on the bean annotated with @ConfigChange to inform the bean about the configuration change.
  • If the configuration subsystem wants to publish further CDI events should be solely in the responsibility of the configuration system used.
As an additional advantage also CDI itself could be configured using the same extension mechanism (see below).

Configuring CDI

Going down the layers CDI itself should be made externally configurable. Hereby one may say we already have beans.xml and  annotations. The problem is that both of these concepts are bound to compile or package time mechanisms. A bundled ear or war archive cannot be changed without opening it, changing it and recreating it with changes included. But this is a thing configuration exactly wants to prevent. Configuration therefore may be provided in a way and with mechanisms that is not controlled by the component to be configured. As a consequence we need a dynamic way for connecting configuration logic with the CDI subsystem that is capable of
  • be available and accessible during deployment/initialization time of the CDI container.
  • be dynamic, so depending on the current valid configuration for a given setup the right values are returned.
Basically this can be achieved most easily by an service provider interface (SPI) defined by CDI. E.g. CDI could add a CDIConfiguration interface as illustrated below that can be configured using the java.util.ServiceLoader.

 public interface CDIConfiguration{
   Collection<Class<? extends Extension>> getExtensions();
   Collection<Class<?>> getAlternativeBeans();
   Collection<Class<?>> getAlternativeStereotypes();
   List<Class<?>> getInterceptors();
   List<Class<?>> getDecorators();
   Collection<String> getScanExcludes();

The problem with this proposal is that adding/enabling things is easy, but disabling things is more complex. But wait! Fortunately CDI comes with a much more powerful concept: CDI extensions, which gives you full access for modifying the CDI metamodel. With that we can
  • Register beans or deadactivate (veto) beans and alternatives.
  • Add, Adapt, Remove injection points
  • Adding or removing interceptors, decorators.
  • Add/remove interceptors, decorators on individual beans
  • ...
So basically CDI extensions already enables us to control CDI. The only thing missing is to define a configuration model, that reflects the different things we want to made configurable. Since we are using a simple Map<String,String> based model, we could e.g. define the following:

// Adding/defining things

// Removing/deactivating things

This configuration basically would enable to configure everything you can do with beans.xml. But we can also think of additional features, e.g.:

// Adding interceptors to a bean

// Adding interceptors to a method on a bean

// Remove an interceptors from a bean

// Remove an interceptor from a method on a bean



The most important outcome for me is that adding application configuration support to CDI does not require CDI to be adapted in any way. CDI already as of now is flexible enough so it can fully support configuration injection, including advanced use cases. This is basically a consequence of the very powerful SPI provided by CDI that allows to adapt the metamodel in a very flexible way. Unfortunately, given the EE configuration initiative seems to be stuck there is only little probability that also all other EE JSRs follow this example and provide similar SPIs, so they can be easily configured without the deployment of xml deployment descriptors. Nevertheless if they do (or would be accordingly enhanced during EE8 work, we could add configuration support in wide areas nevertheless.

As a consequence a standardization initiative as SE standalone JSR would probably be a good variant for starting defining configuration aspects in Java and therefore make corresponding code more interoperable. Such a SE JSR could start very small in a first release, so it could be finished as well within the EE8 timeline. That would enable applications not only to benefit from EE8 in a couple of years, but also having a configuration mechanism in place that is powerful enough to cover many of the aspects in daily live, except those of deployment configuration of the application servers. Such a JSR could define a simple APIs covering the following
  • an API that models configuration and the current runtime environment (util.preferences is not sufficient!)
  • listeners for listening to config changes
  • accessors to access configuration
  • utilities to work buildup configurations
  • optionally also adapting of Strings to objects
  • some functional extension points (operators, queries)
  • an SE based SPI
Such a configuration implementation then could be easily hooked into CDI and all other JSRs as they provide configurable meta-models. thus covering most of the configuration requirements.
More advanced concepts like configuration meta-modelling, building configurations from multiple trees, merging, filtering, security, views and templates would probably be postponed to a later version of such a spec. Nevertheless the reference implementation could provide some of these features, even as pluggable modules, and best practice will show, which of them will qualify to be further standardized at a later point.

Everybody is welcome to comment on this blog. Especially comments and ideas on how specification of configuration aspects should evolve would be very useful.


  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Online Training Java EE Online Training Java EE Online Training Java 8 online training Java 8 online training

    Java Online Training from India Java Online Training from India Core Java Training Online Core Java Training Online Java Training InstitutesJava Training Institutes

  2. Great Article… I love to read your articles because your writing style is too good,
    its is very very helpful for all of us and I never get bored while reading your article because,
    they are becomes a more and more interesting from the starting lines until the end.
    Java training in Annanagar
    Java training in Chennai
    Java training in Chennai
    Java training in Electronic city
    Java training in Marathahalli

  3. Hi there,
    Nice Article I really enjoyed this post Thanks For Sharing,
    Obtain ISO 9001 Certification It enhances your product & service quality, Increases marketing opportunities, Reduces your costs and much more.

    ISO 9001
    ISO 9001 Certification in Mira Road

  4. Hi there,

    Nice Article I really enjoyed this post Thanks For Sharing, check out this
    Ascent ASSOCIATES is one of Sri Lanka’s leading ‘total solutions’ providers, offering a simple, cost-effective route to ISO Certification in Colombo, Kandy, Galle, Dambulla, Sri Jayawardenepura Kotte & all over Sri Lanka.

    Ascent Associates

  5. Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective. Thank you and good luck for the upcoming articles. Check this out

    ISO 22000 Certification in Mumbai

  6. Hey there,
    Enjoyed reading the article above, really explains everything in detail, the article is very interesting and effective, Thanks for Sharing, check this out

    ISO 9001 Certification in Sri Lanka

  7. Never too late to start learning at Salesforce Training in Australia even though you don't have any programming knowledge you can excell in Salesforce Training in London United Kingdom (UK) because it is all about your customers, so this time find the best Salesforce Training in Europe. This way we will learn Salesforce CRM.

  8. Usually, I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up.

    Ascent World

  9. Fantastic blog with excellent information found valuable thank you for sharing.
    Data Analytics Course Online 360DigiTMG

  10. Such an excellent article. Found very interesting and resourceful, I would like to thank you for the efforts you had made for writing this awesome article.
    typeerror nonetype object is not subscriptable

  11. Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
    Cyber Security Course in Bangalore

  12. Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
    Cyber Security Training in Bangalore

  13. This is an excellent article. I like this topic. This site has many advantages. I have found a lot of interesting things on this site. It helps me in so many ways. Thanks for posting this again. PMP Certification in Hyderabad


  14. Fantastic article with informative content. Information shared was valuable and enjoyed reading it looking forward for next blog thank you.
    Ethical Hacking Course in Bangalore

  15. Usually, I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job Man, Keep it up.

    HACCP Certification

  16. They are produced by high level developers who will stand out for the creation of their polo dress. You will find Ron Lauren polo shirts in an exclusive range which includes private lessons for men and women.

    Business Analytics Course in Bangalore

  17. I enjoyed the coursework, the presentations, the classmates and the teachers. And because my company reimbursed 100% of the tuition, the only cost I had to pay on my own was for books and supplies. Otherwise, I received a free master's degree. All I had to invest was my time.

    Data Analytics Course in Bangalore

  18. I have to search sites with relevant information ,This is a
    wonderful blog,These type of blog keeps the users interest in
    the website, i am impressed. thank you.
    Data Science Course in Bangalore

  19. I have to search sites with relevant information ,This is a
    wonderful blog,These type of blog keeps the users interest in
    the website, i am impressed. thank you.
    Data Science Training in Bangalore

  20. I bookmarked your website because this site contains valuable information. I am very satisfied with the quality and the presentation of the articles. Thank you so much for saving great things. I am very grateful for this site.

    Data Science Training in Bangalore

  21. I have voiced some of the posts on your website now, and I really like your blogging style. I added it to my list of favorite blogging sites and will be back soon ...

    Digital Marketing Training in Bangalore

  22. The Extraordinary blog went amazed by the content that they have developed in a very descriptive manner. This type of content surely ensures the participants explore themselves. Hope you deliver the same near the future as well. Gratitude to the blogger for the efforts.

    Machine Learning Course in Bangalore

  23. A good blog always contains new and exciting information, and reading it I feel like this blog really has all of these qualities that make it a blog.

    Artificial Intelligence Training in Bangalore

  24. It is late to find this act. At least one should be familiar with the fact that such events exist. I agree with your blog and will come back to inspect it further in the future, so keep your performance going.

    Digital Marketing Training in Bangalore

  25. A good blog always contains new and exciting information and as I read it I felt that this blog really has all of these qualities that make a blog.

    Data Science Training in Bangalore

  26. I am more curious to take an interest in some of them. I hope you will provide more information on these topics in your next articles.

    Machine Learning Course in Bangalore

  27. Great post happy to see this. I thought this was a pretty interesting read when it comes to this topic Information. Thanks..
    Artificial Intelligence Course

  28. Nice Post thank you very much for sharing such a useful information and will definitely saved and revisit your site and i have bookmarked to check out new things frm your post.
    Data Science Course

  29. Thanks Your post is so cool and this is an extraordinary moving article and If it's not too much trouble share more like that.
    Digital Marketing Course in Hyderabad

  30. You have done excellent job Thanks a lot and I enjoyed your blog. Great Post.
    Data Science Certification in Hyderabad

  31. Very great post which I really enjoy reading this and it is not everyday that I have the possibility to see something like this. Thank You.
    Best Online Data Science Courses

  32. Very informative blog! There is so much information here that can help thank you for sharing.
    Data Science Syllabus

  33. Hi, I looked at most of your posts. This article is probably where I got the most useful information for my research. Thanks for posting, we can find out more about this. Do you know of any other websites on this topic?
    Data Science Course Details

  34. A good blog always contains new and exciting information and as I read it I felt that this blog really has all of these qualities that make a blog.

    Ethical Hacking Training in Bangalore

  35. Superb Information and really appreciated with it and this is fine to read and valuable. I like it.
    Digital Marketing Course fees in Hyderabad

  36. Your website is really cool with great inspiring articles and thanks for sharing this amazing and educative blog post!
    Cloud Computing Courses in Hyderabad

  37. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work thank you.
    Cloud Computing Training in Bangalore

  38. This is truly an practical and pleasant information for all and happy to see this awesome post by the way thanks for sharing this post.
    Data Scientist Course in Noida

  39. Thank you for posting this information. I just want to let you know that I just visited your site and find it very interesting and informative. I look forward to reading most of your posts.

    Data Science Course in Patna

  40. It would also motivate almost everyone to save this webpage for their favorite helper to help get the look published.

    Data Science Training in Patna


  41. I am sure it will help many people. Keep up the good work. It's very compelling and I enjoyed browsing the entire blog.
    Business Analytics Course in Bangalore

  42. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work thank you.
    Data Analytics Course in Chandigarh

  43. Very useful message. This is my first time visiting here. I found a lot of interesting things on your blog, especially your discussion. It really is a great article. Keep on going.

    Data Analytics Course in Ernakulam

  44. Very nice job... Thanks for sharing this amazing and educative blog post!
    Data Science Training in Lucknow

  45. I read your excellent post. It's a great job. I enjoyed reading your post for the first time. I want to thank you for this publication. Thank you...

    Data Analytics Course in Patna

  46. Very informative Blog! There is so much information here that can help thank you for sharing.
    Data Science Training in Lucknow

  47. Good blog and absolutely exceptional. You can do a lot better, but I still say it's perfect. Keep doing your best.

    Data Science Training in Durgapur

  48. I am here for the first time. I found this table and found it really useful and it helped me a lot. I hope to present something again and help others as you have helped me.

    Business Analytics Course in Nagpur

  49. Excellent effort to make this blog more wonderful and informative. The information shared was very useful.
    Data Analytics Course in Chandigarh

  50. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work thank you.
    Business Analytics Course in Chandigarh