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();
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()
{
}
}
Guice does not support this by default, but possibly my answer to another question can help you to get something going.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With