Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 655
Vasiliy Avatar asked Jun 22 '17 05:06

Vasiliy


1 Answers

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.

like image 180
Paul Samsotha Avatar answered Oct 24 '22 09:10

Paul Samsotha