清理@RequestScoped对象?

时间:2011-01-19 18:40:31

标签: java guice

我正在使用guice-servlet(2.0)在每个HTTP请求的开头注入数据库连接,但是如何找到请求何时结束以便我可以关闭连接?

的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();

2 个答案:

答案 0 :(得分:5)

这在Guice 2.0中是不可能的。一种解决方法是注册一个自定义servlet侦听器,在每个请求结束时关闭Connection:

/**
 * 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()
    {
    }
}

答案 1 :(得分:1)

Guice默认情况下不支持此功能,但可能我的answer另一个问题可以帮助您实现目标。