Application configuration in JEE

Over the past years, the Spring Framework has given us many tools to simplify ease of application development.

One of the nicer features is Spring’s PropertyPlaceholderConfigurer, a BeanPostProcessor implementation that allows you to inject values from property files into your managed beans, making application configuration a breeze.

Setting up one is a little bit of xml configuration:

And then you can inject property values from your property file:

JEE doesn’t have a PropertyPlaceHolderConfigurer right out of the box so we have to come up with a different solution.

What JEE offers are producer methods. A producer method is a method that constructs an object of an arbitary type which can then be used by Context Dependency Injection (CDI) as a candidate for injection.

Producer methods use the @Produces annotation for indicating the kind of object it will produce.
The kind is indicated by the produced type and, optionally, a qualifier annotation.

Say that you want to indicate that some properties should be injected in your client class. We will put an custom annotation @ConfigurationValue on each field to indicate the field value should come from a property.

where you want to explicitly specify the property key on the first field to be populated, and just use the field name as a property key on the second field.

The qualifier @ConfigurationValue used by the object that requires configuration would look as follows:

The meta-annotation @Qualifier here indicates this annotation can be used for JEE’s CDI qualifying mechanism.

Now, we have to write a producer method that responds to fields using the @ConfigurationValue annotation.

An example of a producer method that retrieves its property values from a properties file could be the one below.

Of course, this only works for strings now, but it would be easy to extend in such a way that you would support numerical types as well, through multiple producer methods.

Posted in Coding | Comments Off on Application configuration in JEE