dependency-injectionjersey-2.0hk2servletcontextlistener

Inject dependencies into ServletContextListener using HK2 in Jersey


In order to initialize the application at startup, I extended ServletContextListener:

@WebListener
public class MyServletContextListener implements javax.servlet.ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ... initialization code here
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {}
}

Now I want to extract the initialization logic into a standalone StartupManager class, and delegate to this class from MyServletContextListener:

public class StartupManager {

    public void performStartup() {
        ... initialization code here
    }
}

I tried to inject StartupManager into ServletContextListener by simply adding @Inject annotation:

@WebListener
public class MyServletContextListener implements javax.servlet.ServletContextListener {

    @Inject StartupManager mStartupManager;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        mStartupManager.performStartup();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {}
}

This did not work - the reference is null when contextInitialized(ServletContextEvent ) is called.

Then I thought that I might have to register a binder:

@ApplicationPath("")
public class MyResourceConfig extends ResourceConfig {

    public MyResourceConfig() {
        register(new DependencyInjectionBinder());
    }
}

public class DependencyInjectionBinder extends AbstractBinder {
    @Override
    protected void configure() {
        bind(StartupManager.class).to(StartupManager.class);
    }
}

This did not work either.

My question is how can I perform injection of dependencies into ServletContextListener? Preferably constructor injection, but field injection will also be alright.


Solution

  • It's not going to work, as the servlet listener and Jersey are not linked to the same system. As an alternative, you can use Jersey's Event Listeners. You can implement an ApplicationEventListener where you would be able to initialization and clean up in the same way you would in the servlet listener. You would be able to inject your services into Jersey's listener.