Daniel Walton
Daniel Walton

Reputation: 113

Add Guice dependency Injection to Servlets configured in web.xml

I'm using Guice in a project for dependency injection into Servlets. We have a ServletModule that defines the serve().with() configuration. This all works fine.

I now need to be able to include a webapp with servlets defined in the web.xml. All of the documentation says add GuiceFilter to web.xml and then use the programattic config in the ServletModule, but I'm wondering if it's possible to get Guice to inject dependencies into servlets configured in web.xml?

I want to be able to define servlets in web.xml eg:

 <servlet>
   <servlet-name>test</servlet-name>
   <servlet-class>TestServlet</servlet-class>
 <servlet>

When the servlet is created the container just called the no-arg constructor. Can this behaviour be changed so that Guice creates the servlet and injects at creation time?

Upvotes: 2

Views: 576

Answers (2)

tariksbl
tariksbl

Reputation: 1109

injector.injectMembers(obj) explicitly sets @Inject fields:

@Inject Foo foo;

TestServlet()
{
    // wherever your injector instance is defined
    ...getInjector().injectMembers(this);
}

The docs recommend getInjector().getMembersInjector().injectMembers() though I haven't used this.

Upvotes: 2

ZhongYu
ZhongYu

Reputation: 19682

You probably need to use Guice as a service locator in TestServlet.

    TestServlet(Foo foo){ ... } // please inject foo!

    TestServlet()
    {
        this( MyGuiceServletConfig.injector.getInstance(Foo.class) );
    }

--

public class MyGuiceServletConfig extends GuiceServletContextListener {

    public static final Injector = Guice.createInjector(new MyServletModule());

    @Override
    protected Injector getInjector() {
      return injector; 
    }
}

(they say DI frameworks are not intrusive :)

Upvotes: 1

Related Questions