Wednesday, September 18, 2013

Manual Dependency Injection with Jersey and embedded Jetty

I wrote a little application demonstrating how to manually (through constructors) inject dependencies into Jersey resources in an embedded container like Jetty. 

The benefits are:
- lightweightness (no need to use Spring, Guice, etc.),
- more control over your application (less magic behind the scenes),
- controlling dependencies in tests (via Dependency Injection)
- running a web app with a simple Java main method (via embedded Jetty)

The example application is called Time Expert. It exposes the current time via a RESTful web service, so when I run it in the production (via Main.java) I can use it as following:

Here's how I test it (TimeAcceptanceTest.java) :

However,  I cannot rely here on the real time because it changes every time I run tests . The problem can be easily solved with the Clock pattern. My tests require a FixedClock which allows me to set the current time to any value:



 So I start my server with a fixed clock:


... and then set it to, say, 20:15:


Since my Jersey resource class is only aware of the clock interface, it will display 20:15:


In order to create your Jersey resources with manually injected dependencies you have to register org.glassfish.jersey.servlet.ServletContainer with a customized org.glassfish.jersey.server.ResourceConfig. In that config Jersey resources can be newed up with their dependencies:

Of course the production provides a real clock (which returns new Date()):


Code is available under: https://github.com/unclejamal/TimeMaster

Enjoy!

Tested using:
- Java 1.7,
- Gradle 1.7 (easily convertible to Maven :)),
- Jersey 2.2,
- Jetty 9.0.5.