Thursday, March 15, 2007

My First Guice Web Application

Google Guice is an open source Dependency Injection framework from Google. Guice is based on annotations and generics unlike Spring which depends on XML of Java for wiring dependencies. Guice injects constructors, fields and methods (any methods with any number of arguments, not just setters). Guice provides support for custom scopes, static member injection, Spring as well as Struts 2.x integration and AOP Alliance method interception. Guice is available at Google Code. You can find the User guide and Javadocs from there. This post describes how I implemented a simple Web application using Guice. For injecting dependencies into Servlets, I used a Listener (this idea was from Hani Suleiman in the Guice developer mailing list). Follow these steps to run the example.
  1. Download Guice from the Guice Site.
  2. Create the Service Interface and Implementation: These are fairly simple as shown below
    package services;

    public interface Service {
    public String doWork();
    package services;

    public class ServiceImpl implements Service {

    private int count = 0;
    public String doWork() {
    System.out.println("Service Impl Doing work " + count);
    return("ServiceImpl : " + count);
  3. Create an Annotation: Guice allows you to select which implementation of an Interface you want to inject, by using annotations. You will see this used in the TestServlet. Here is the annotation I defined
    package annotations;

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;


    @Target( { ElementType.FIELD, ElementType.PARAMETER })
    public @interface MyAnnotation {

    • @Rentention(RUNTIME) makes the annotation visible at runtime.(this is mandatory when using Guice)
    • @Target({FIELD, PARAMETER}) prevents the annotation from being applied to methods, types, local variables, and other annotations.(This is optional)
    • @BindingAnnotation is a Guice-specific signal that you wish your annotation to be used in this way. Guice will produce an error whenever user applies more than one binding annotation to the same injectable element. (This is necessary when used for binding with Guice)
    • Optionally, you can also use annotations with attributes to differentiate between bindings.
  4. Create a Guice Module: Guice Modules are used to define bindings within an applications. It is possible to have multiple modules per application (and multiple applications can share a common module too). Here is the simple Module that I implemented.
    package modules;

    import services.Service;
    import services.ServiceImpl;
    import annotations.MyAnnotation;


    public class MyModule extends AbstractModule {

    public void configure() {

    • Guice provides the module with a binder which is used to bind the Interfaces with implementations.
    • annotatedWith(MyAnnotation.class) defines the binding to the implementation based on the annotation.
    • in(Scopes.SINGLETON) is used to define this implementation as a Singleton
  5. Create a Listener: Here is the Code for a simple listener (for a more complete example see the above mentioned mailing list).
    package listeners;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletContextEvent;
    import javax.servlet.ServletContextListener;

    import modules.MyModule;


    public class GuiceServletContextListener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    public void contextInitialized(ServletContextEvent servletContextEvent) {
    Injector injector = Guice.createInjector(new Module[] { new MyModule(), new ServletModule() });
    ServletContext servletContext = servletContextEvent.getServletContext();
    servletContext.setAttribute(Injector.class.getName(), injector);
    • The listener is used to save the Injector in the servlet context to be used in the AbstractInjectableServlet.
    • An injector is to be built during startup and used to inject objects at runtime.
    • ServletModule is used for servlet-specific bindings. It adds a request/session scope, as well as allowing the injection of request,response, and request parameters into your beans. To use it you have to register GuiceFilter in your web.xml.
  6. Create an Abstract Servlet: The AbstractInjectableServlet will be super class of all the Servlets you use. This class uses the injector to inject dependencies in the concrete classes by the injector.injectMembers(this) method.
    package servlets;

    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;


    public abstract class AbstractInjectableServlet extends HttpServlet {

    public void init(ServletConfig config) throws ServletException{

    ServletContext context = config.getServletContext();
    Injector injector = (Injector) context.getAttribute(Injector.class.getName());
    if (injector == null) {
    throw new ServletException("Guice Injector not found");

  7. Create the Test Servlet: Here is the code for the TestServlet
    package servlets;


    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import services.Service;
    import annotations.MyAnnotation;


    public class TestServlet extends AbstractInjectableServlet implements javax.servlet.Servlet {

    private Service service;
    public TestServlet() {

    public void setServiceInstance(@MyAnnotation Service service) {
    this.service = service;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().println("Service instance : " + service.doWork());
    • The @Inject is used to define methods to be injectable.
    • The @MyAnnotation for the Service parameter means that, the actual binding will be done with the implementation that is bound using the withAnnotation() method.
  8. The Web Deployment Descriptor
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.4"




  1. I know it isn't directly relevant to Guice, but the ServiceImpl class is not thread-safe: the count field is accessed without any kind of synchronization. A simple way to fix it would be to wrap the counter increment in a synchronized block like this:

    int c;
    synchronized (this) { c = count++; }

    and use c instead of count in the trace message and the returned string.

    Tim Peierls

  2. Well, this is a nice thing to get some articles collected from various sites. but I think the owner of this blog should give some examples rather than copy/ paste.

    something is burning...ego hurted....:)))

  3. Thank very much Abhi is just that i looking for! great post!

  4. Good Job Abhi Good effort All the best- Blogger Chaala Bagundi :)

  5. the AbstractInjectableServlet class is already implemented in Guice and teh class is

  6. warp-servlet provides a much nicer version of injectable servlets, as it stands neither AbstractInjectableServlet nor InjectedHttpServlet are capable of:

    constructor injection
    aop interception
    cyclical ctor injection

    warp-servlet allows your servlets and filters to benefit from all of this, and more scopes.

  7. Hi,
    I found your article excellent and in my company ( we used your example as a startup for our application.


  8. I guess you could omit the ElementType.PARAMETER for MyAnnotation because you only use it on a parameter. BTW you can also do constructor and local variable annotations accordingly.

  9. I am Aditi webmaster of Zed-Axis Technologies Pvt. Ltd Software Development Company Microsoft Certified, IT Solutions Company, offering Custom Software application development and web site development in India.

  10. It is great to read article about web application development.
    Web Application Development Company

  11. Thanks for providing valuable information.
    If your interested app development please connect us on SSI!

  12. I am here after long google. thanks for this post.
    If you interested app development please connect us on Sagacity Solutions India


Popular Posts