Sunday 8 May 2016

In My Toolbox: CDI


One thing that Java developers may not complain about their ecosystem is choice. There is so much choice in Java, at all levels, that it may seem sometimes daunting. What to choose when getting the job done?

Take Dependency Injection*), for example. Besides well established names like J2EE servers or Spring, we have lightweight, standalone solutions such as Google Guice or PicoContainer.

The disadvantages of Spring, Guice or PicoContainer are … well … their lack standardization. If you choose to work with any of them then you’re bound to their semantics (although Spring starts to move towards supporting the standard semantics of dependency injection from Java Enterprise) which is the open-source variant of vendor lock-in.

So, for standard-compliant dependency injection we’re pretty much stuck with an application server … or not? Actually not, because – thanks to the wonderful standardisation process of Java – we do have server-independent dependency injection. Java CDI is the name and it was formalised over various JSRs (I know of 299, 330, 346 and 365).

To sweeten the deal, there is a good-quality implementation: JBoss Weld. Weld can be (and it is) used in application servers, web servers or servlet containers or (and this is what I am talking about) it can be fired up straight away from a plain, simple, Java executable.

How It Works

I’ll show portions of the code of a small web server application which I wrote today. It embeds Jetty for web infrastructure, it makes use of Apache Wicket as a web framework and it encapsulates command line parsing (i.e. Apache CLI) in a class aptly named as CmdLine: