Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up a @RequestScoped object?

Tags:

java

guice

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();
like image 771
Gili Avatar asked Jan 19 '11 18:01

Gili


2 Answers

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()
    {
    }
}
like image 129
Gili Avatar answered Oct 31 '22 14:10

Gili


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

like image 28
Waldheinz Avatar answered Oct 31 '22 15:10

Waldheinz