Tag Archives: cdi

Property Injection with CDI

Over the last several months, I’ve been working on a large enterprise web application development effort using Java EE 7. As a long user of the Spring Framework for Java web application development, one of the things I immediately missed were the simple property injection techniques supported by Spring’s PropertyOverrideConfigurer and PropertyPlaceholderConfigurer.

Out of the box, CDI provides no good solution for property injection. However, CDI’s really outstanding extension mechanism makes it really easy to get CDI to do things that it doesn’t inherently support. I made a CDI extension named Pinject that provides all of the property injection support needed by the typical Java web application.

It’s as simple as this:

[java]
package com.example.myapp;

public class MyBean implements MyService {

@Inject
@Property
private URL location;

@Inject
@Property
private int maxRetries;

}
[/java]

And we place a properties file named beans.properties on the classpath containing the
values to inject:

[java]
com.example.myapp.MyBean.location=http://www.google.com
com.example.myapp.MyBean.maxRetries=3
[/java]

Pinject provides a great deal of flexibility in resolving and converting property values and injecting them into your beans. It even provides its own extension points so that you can easily cover use cases I didn’t think to provide. Please check it out and let me know if you find it useful.