Tuesday, April 10, 2012

JSR 330 : Contexts and dependency injection for the Java EE platform

Using the JSR 330 API is pretty simple. First you define an injection point in a class, which wants to use a concrete implementation of a service
// injection-point; no get/set needed... 
@Inject private BusinessService service; 
Next you need to provide an actual implementation
public class DefaultBusinessService implements BusinessService {
...
}
If you have more versions of this service, you have to create a Qualifier annotation:
@Qualifier
@Target( { TYPE, METHOD, FIELD })
@Retention(RUNTIME)
public @interface FancyService
{
}
You use the Qualifier to inject a more meaningful implementation of the service :
@Inject @FancyService private BusinessService fancyService;
As you see, using JSR 330 is pretty simple. So, what's the drawback with this solution?

Injecting a service using annotations is an ok approach, but what I don't like is the lack of configuration options.  What would for instance happen if I create two different implementations of the BusinessService interface and want to inject these two into different beans? Do I then have to also create two qualifier interfaces to distinguish between them? To me that sounds lame.

A possible JSR 330 implementation might configure it's beans in one major XML file. Would it be so hard to for instance have the qualifier configuration there instead? The benefits would be:
  • No compile time dependencies to one given qualifier interface
  • Changing the business service would just be a mather of changing the XML file
JSR 330 might work in a standalone project where the configuration never changes, but I really don't see how this should work in a large software system where configuration and requirements can change pr customer and installation...

No comments:

Post a Comment