Tag Archives: DI Container

REST with Java in practice

RESTful web services are generally hyped these days – and for many good reasons: among others, the fact that they are easily consumed by almost any kind of client – browsers, mobile apps, desktop apps etc.

One technology stack for building restful services in a Java environment could comprise Jersey, Gson and Guice (nice alliteration, by the way…). Without prior knowledge to any of these technologies, me and my team managed to successfully establish a RESTful web service consumed by for example this website.

I will briefly introduce these 3 frameworks:

Jersey and JAX-RS

Jersey­ is one of several implementations of the JAX-RS interface – the Java API for RESTful web services.

Jersey provides a servlet that analyses an incoming HTTP request by scanning underlying classes for RESTful resources, and selecting the correct class and method to respond to this request. The RESTful resources are defined by decorating classes and methods with the appropriate JAX-RS annotations.

If you for example have a UserService class that you want to expose through a RESTful API, you can wrap it in a UserWebService class and decorate this class and its methods with JAX-RS annotations:

The @Path annotation specifies on which (relative) URL path this method will be invoked. The @Get annotation specifies that the http method GET has to be used and the @Produces annotation declares the format of the response.

So, the following http-request:

GET http://localhost:8080/myservice/api/user/list

will invoke the GetUserList() method, which basically is a pass-through to the UserService.getAll() method, and return a response with a list of users in JSON format.

JSON support using Gson

One of the decisions you have to make when establishing a RESTful service is which representation formats (media types) to support. Very often JSON will be the obvious choice – especially if the services are to be consumed by browser-based clients which typically use JavaScript.

In order to produce and consume JSON you need a serialization mechanism that turns a Java object into a JSON document and vice versa (under-the-hood the representation bodies will very often be POJO objects). Our choice was to use Google Gson for this purpose.

You simply need to implement the two interfaces javax.ws.rs.ext.MessageBodyWriter and javax.ws.rs.ext.MessageBodyReader, and decorate the implementing classes with the JAX-RS @Provider annotation. Here is the writer:

And here is the reader:

Guice as DI container

In a previous post I showed how to use Guice as a DI container in a Jersey application. So, what is left now is to bind the Gson writer and reader – ass well as other types, such as the RESTful resource classes – in the Guice injector:

To summarize, a well-proven technology stack for implementing a RESTful web service in Java comprises Jersey­ as the REST framework, Google Guice as the DI container to support dependency Injection and Google Gson for JSON serialization and de-serialization of the representation body objects. The service can be deployed on for example a Glassfish server.

Implementing Role-Based Authorization using Guice

Besides magically composing the entire object graph for your application, one of the main advantages of introducing a DI container is its ability to perform runtime interception. Because you are delegating the responsibility of composing objects to a 3rd party component (the DI container) you also give this container the possibility to intercept a call from the consumer to a service and execute some additional code before passing the call on to the service itself.

This is a perfect way to implement cross-cutting concerns (aspects) such as logging, validation, authorization etc. so that the underlying services don’t have to care about this and can easily follow the Single Responsibility Principle.

In this post, I will show you an example of how to implement role-based authorization using aspect oriented programming (AOP) in Guice.

The example is a RESTful web service built using Jersey­. The web service is ­using the basic authentication scheme which forces the client to authenticate itself with a user ID and a password for each request. The client must compute a Base64 encoding of <user>:<Password> and include the value in an Authorization header in the request.

The web service operates with 4 different roles: Guest, User, Editor and Admin.

The roles are meant to be hierarchical in the sense that e.g. an editor inherits all the privileges of a guest and a user. This is done by defining a RoleSet enum with an abstract method called getRoles(), which each enum has to override.

So each user does not have a role, but a role set. Through the hasRole() method it can be queried whether a user has the privileges of a particular role:

Now, to setup the role-based authorization, you need to do the following:

  1. Create a new annotation
  2. Implement the method interceptor
  3. Decorate the methods that must be protected with the new annotation
  4. Register the interceptor

Creating the annotation

First, you need to define an annotation that can be used to decorate the methods that you want protected by role-based authorization:

Implementing the interceptor

The interceptor itself is made by implementing the org.aopalliance.intercept.MethodInterceptor interface:

Through the methodInvocation variable, the interceptor has the opportunity to inspect the call: the method, its arguments, and the receiving instance. In this case, you will inspect the httpHeaders argument to get and parse the Authorization header of the http request. The Authorization header includes a Base64 encoding of <user>:<Password>, so you can decode this string and extract the username and password of the caller. The required role is extracted from the @Authorize annotation. If the calling user does not have the required role, or if the provided password is wrong, an appropriate exception is raised. Otherwise, the intercepted method is allowed to proceed.

Decorating the methods

The usage of the @Authorize annotation is straight-forward, simply decorate the method and declare the required role in the annotation parameter.

Register the interceptor

Finally, the interceptor needs to be registered. You need to create matchers for the classes and methods to be intercepted. In this case you must match any class – but only the methods decorated with the @Authorize annotation. Because you need to inject dependencies into the interceptor, use requestInjection() alongside the standard bindInterceptor() call.

As for all other calls to Guice methods, this code must reside in the bootstrapper component of the application where the whole object graphs is wired up.

Now, if a method decorated with the @Authorize annotation is called, the autorizationInterceptor will be executed before the method itself. This is Guice and AOP in action.

Dependency Injection with Java using Guice

I generally code in .NET, and in a previous post I described how to use Microsoft Unity as the DI container in a ASP.NET MVC project. Also, the whole inspiration to dig into DI came from the book Dependency Injection in .NET. However, the first “real-life” project where I decided to let DI be the driving design principle happened to be a Java-project…

Anyway, that constraint turned out to be no problem whatsoever – thanks to the fact that the above mentioned book reaches way beyond the .NET framework in the description of DI techniques, and the fact that Google provides the terrific DI container Guice for Java.

One of the golden rules of DI is not to “new” up objects. Guice introduces the @Injection annotation as an alternative to the new keyword. You can think of @Injection as the new new

To prepare for constructor injection, you have to add the @Inject annotation to your constructor:

Then, during object composition, all of the dependencies of that constructor will be automatically filled in by Guice.

You might argue that by adding this @Inject annotation, you add a dependency in your UserService class to Guice itself. However, Guice does support the standard JSR 330 annotations, so you actually don’t need to introduce Guice specific annotations in your code at all.

When composing the object graph, Guice uses bindings to map types to their actual implementations. The bindings define how dependencies are resolved during object composition. For example, to tell Guice which implementation to use for the IRepository<User> interface, you will need linked binding. The below example maps the IRepository<user> interface to the UserRepository class using the to() clause.

Note that because IRepository<User> is a generic interface, an anonymous subclass of TypeLiteral must be used in the declaration.

Now that the IRepository<user> interface mapping is in place, you can use untargeted binding to bind the concrete UserService class. An untargeted binding has no to() clause:

All the binding declarations must be gathered in the configure() method of a module. A module is a class extending the AbstractModule class:

The actual object composition is done using a so called injector:

Obviously, this kind of code shall not be scattered all over your code base. All calls to Guice types – including the injector – should be isolated in some top-level component – the composition root (bootstrapper) of the application where the whole object graphs must be wired up.

I showed in a previous post how ASP.NET MVC has built-in support for the Unity DI-container. Likewise, Jersey­­ – the Java library for building REST API’s – has seamless support for Guice so that you don’t have to manually call the getInstance() method to create objects. Guice Servlet provides a utility that you can subclass in order to register your own ServletContextListener:

To create a Guice injector you need to pass a JerseyServletModule where you are overriding the configureServlets() method. In here you must define the Guice bindings.

As most other DI containers, Guice also provides Lifetime management. The lifetime of objects can be handled through scopes. Guice supports the scopes singleton, session and request . Scopes can be configured in the bind statements using the in() clause. Here is an example of setting the scope of the user repository to singleton:

The final Guice feature I will mention is support for method interception through aspect oriented programming. This is a very powerful feature for solving cross-cutting concerns such as logging or authorization in your application. In a later post I will show how to implement role based authorization using aspect oriented programming in Guice.

Putting it all Together – DI part 4

Dependency Injection – and the low coupling between components that it leads to – goes hand in hand with high cohesion. It is now time to grab the individual components and put them together to form a “real” application.

In the first post in this series, it was explained how the whole point of dependency injection is to remove the burden of composing objects away from the individual components themselves, and instead delegate this responsibility to a single well-defined location as close as possible to the entry point of the application – also denoted the composition root of the application.

This object composition can very well be done manually by simply “newing” up all the objects – which is sometimes referred to as “poor man’s DI” – but a good alternative is to leave the responsibility of solving the object graph to a DI container. A DI container is a third-party library that can automate the object composition and lifetime management. Furthermore, some DI containers support runtime interception which is a very powerful technique for solving cross-cutting concerns such as logging or authorization (more about this in a later post).

And yes, when using a DI container you are, ironically enough, introducing a new dependency to solve the dependencies! But obviously, the DI container object itself should be created manually, and the DI container library should only be referenced from the composition root.

Anyway, here is an example of wiring up the application using Microsoft’s DI container called Unity in an ASP.NET MVC application. Adding a reference to the Unity.Mvc3 library (for example using the NuGet Package Manager) will automatically create a static helper class called Bootstrapper. In the BuildUnityContainer() method you need to register which concrete type should be mapped to the IRepository<Product> abstraction during run time. In this case an XmlProducRepository class is used. XmlProductRepository itself has a dependency to a string defining the path to the XML file used as physical repository.

To use ProductService in one of the controllers (e.g. the HomeController), you need to inject ProductService using constructor injection:

That’s it. The DI container takes care of the rest.

The first time you are introduced to the concept of DI containers you might become a bit mystified, and even worried, about all the “magic” that apparently goes on behind the scenes. I certainly know that I was. However, trying to dig a bit deeper into what actually goes on might help on this scepticism. This is what happens during an incoming request to go to the Home page of the application:


MvcApplication receives a request to go to Home the page. The DependencyResolver is asked to resolve HomeControler (i.e. create the whole object graph) – and this is where the magic starts! The dependency resolver detects the dependencies (HomeControler -> ProductService -> IRepository<Product> -> string) and starts creating the object graph from the bottom and up. First an instance of ProductRepository is created. During registration you declared that this was the concrete type to be used for the IRepository<Product> abstraction. You also declared the path to the physical file “c:\data\repository.xml” during registration. Then this ProductRepository instance is injected into ProductService, using constructor injection, when creating the ProductService instance. Finally, this ProductService instance is injected into the HomeController when creating the HomeController instance. The dependency resolver has done its job for this incoming request.

Subsequently, the Index() method of the HomeControler is called and the HomeController can use the injected ProductService to retrieve a list of products, which can then be displayed in the browser.

This is how the dependency graph of your application looks:


MvcApplication (found in the Global.asax file) acts as the composition root taking care of object composition. The business component has no dependencies to other components, so the Dependency Inversion Principle is still respected.