6

I am using guice-servlet (2.0) to inject a database connection at the beginning of each HTTP request, but how can I find out when the request ends so I can close the connection?

web.xml

<filter>
    <filter-name>Guice Filter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>Guice Filter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

GuiceServletContextListener

/**
 * Creates a new Database connection.
 */
@RequestScoped
@Provides
private Connection getConnection();
Gili
  • 86,244
  • 97
  • 390
  • 689

2 Answers2

6

This isn't possible in Guice 2.0. One workaround is to register a custom servlet listener that closes the Connection at the end of each request:

/**
 * Closes SQL connections at the end of an HTTP request.
 * 
 * @author Gili Tzabari
 */
public class ConnectionFilter implements Filter
{
    private final Injector injector;

    @Inject
    public ConnectionFilter(Injector injector)
    {
        this.injector = injector;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                                             FilterChain chain)
        throws IOException, ServletException
    {
        Session session = injector.getInstance(Session.class);

        try
        {
            chain.doFilter(servletRequest, servletResponse);
        }
        finally
        {
            session.close();
        }
    }

    @Override
    public void destroy()
    {
    }
}
Gili
  • 86,244
  • 97
  • 390
  • 689
1

Guice does not support this by default, but possibly my answer to another question can help you to get something going.

Community
  • 1
  • 1
Waldheinz
  • 10,399
  • 3
  • 31
  • 61