Using Google Guice in Web Applications

Introduction

As promised in the previous article I’ll continue presenting Google Guice also for web applications. In order to do this you’ll need to get the servlet extension – part of the standard distribution, along with other extensions like JMX, JNDI, Persist, Struts or Spring. Using Guice, the web.xml will be reduced at minimum – just make the Guice container start. The rest of the configurations will be easily done in Java in the same type-safe manner presented in the previous article.

The servlets will benefit from:

How to inject Spring beans into Servlets

This can be achieved in 3 simple steps:

1. Implement HttpRequestHandler

First of all your servlet class must implement the org.springframework.web.HttpRequestHandlerinterface and provide an implementation for the handleRequest() method just like you would override doPost().

2. Declare the servlet as a Spring Bean

You can do this by either adding the @Component(“myServlet”) annotation to the class, or declaring a bean with a name myServlet in applicationContext.xml.

   @Component("myServlet")
   public class MyServlet implements HttpRequestHandler {
...

3. Declare in web.xml a servlet named exactly as the Spring Bean

The last step is to declare a new servlet in web.xml that will have the same name as the previously declared Spring bean, in our case myServlet. The servlet class must be org.springframework.web.context.support.HttpRequestHandlerServlet.