bashan
bashan

Reputation: 3602

Guice injection doesn't work in ServletContextListener

Is the a reason why Guice injection doesn't work in a ServletConextListener?

Here is my code:

public class QuartzContextListener implements ServletContextListener {

    @Inject
    private DataAccess dataAccess;


    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println(dataAccess);
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

Of course that:

Any idea?

Upvotes: 1

Views: 1421

Answers (2)

sargue
sargue

Reputation: 5875

It won't work because Guice is not creating the instance of your QuartzContextListener. If you are using GuiceServletContextListener I suggest to use just one listener (Guice's one) and call yours from that one.

If that solution is not possible you can try the workaround of using static injection. Be careful, thought, because you say Guice is bootstraped before your listener but that may not be always the case.

To use static injection you can change your listener definition like this:

public class QuartzContextListener implements ServletContextListener {

    @Inject
    private static Provider<DataAccess> dataAccessProvider;

    ...
}

And then, from one of your Guice modules, request an static injection.

requestStaticInjection(QuartzContextListener.class)

Upvotes: 1

Humberto Pinheiro
Humberto Pinheiro

Reputation: 1174

What about extending GuiceServletContextListener:

class Example extends GuiceServletContextListener {
        @Override
        protected Injector getInjector() {
            return Guice.createInjector(new MyGuiceModule(), new MyGuiceServletModule());
        }
    }

Upvotes: 0

Related Questions