How do I start/stop a service in a web application with Guice

417 views Asked by At

I'm building a web application and I'm using the Guice Servlet extension to bootstrap everything.

Following the user guide and examples I found, my web.xml has a single listener which extends GuiceServletContextListener. In my listener, I create my injector as described here.

My app has a few components which need to be initialized and destroyed when the servlet context is initialized and destroyed respectively. Some examples are a cache manager, a client which fetches data from a 3rd party API, a client to access a Cassandra store, etc.

I'm trying to find the right place to init/destroy these components. Without Guice, I would probably do that directly in my context listener, but it seems that Guice doesn't promote that.

What I have seen is the use of a servlet filter for each service. By implementing init/destroy in each filter, I can start and stop each service. However, if I have no actual filtering to do, this seems like overkill just to hook into the servlet lifecycle:

@Singleton
public final class MyServiceFilter implements Filter {
    private final MyService service;

    @Inject
    public MyServiceFilter(MyService service) {
        this.service = service;
    }

    @Override
    public void init(FilterConfig filterConfig) {
        service.start();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        service.stop();
    }
}

Are there any other options?

0

There are 0 answers