Inject Properties using CDI

One of the principal goals of CDI is to make the Java EE programming model far more extensible - from adding basic functionality to full-scale integration with third-party software. Piotr Nowicki demonstrates this well by doing something pretty simple but common and useful - injecting a value from a Java .properties file into any managed bean using CDI @Produces and InjectionPoint. Note that the Core module of the Apache DeltaSpike project also includes similar functionality. In case you are unaware of Apache DeltaSpike, it is the de-facto collection of CDI portable extensions (it is the successor to both Seam 3 and Apache CODI).

Both Piotr's code and Apache DeltaSpike inject values from property files only. One useful addition could be to also support Java environment variables. Perhaps this inspires you enough to create your own CDI portable extension for injecting properties or contribute to DeltaSpike :-)? Interestingly, there is a similar discussion on JAVAEE_SPEC-19. Perhaps this is an area for the emergent Java EE Configuration JSR to look into?

Comments:

DeltaSpike does support environment variables out of the box (as well as system properties and JNDI entries, see Javadoc of org.apache.deltaspike.core.spi.config.ConfigSource).

It is rather easy to implement a custom ConfigSource and register it via META-INF/services. No need for an additional CDI portable extension.

Posted by Harald Wellmann on February 17, 2014 at 10:01 AM PST #

Thanks for the note, will keep in mind going forward.

Posted by Reza Rahman on February 18, 2014 at 09:14 AM PST #

Configuration Injection as shown will definitively by a topic for Java EE configuration. One of the issues of injecting String directly is, that - since its a final class - it cannot be proxied. Therefore you will not be aware of any configuration changes (the injected value will never change), even when the underlying configuration has been changed. This can be handled in different ways and would be an interesting topic for a follow-up:
- providing some change events, so an injected class can observe changes relevant to it (they can be tailored, so an instance only sees changes relevant).
- using an indirection for accessing values. With the current CDI standard, you might inject an Instance, for example, but we have to discuss additional features may require something additional to be modeled...

I also have just started a blog (http://javaeeconfig.blogspot.ch), where I plan to publish regular blogs on the topic of Java configuration to keep the discussions ongoing...

Posted by Anatole Tresch on March 18, 2014 at 04:55 AM PDT #

Anatole,

Thanks for your comments - please do feel free to drop me an email when you have new content so we can help get the word out.

Cheers,
Reza

Posted by Reza Rahman on March 18, 2014 at 07:50 AM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed