2011-01-19 82 views
6

我使用guice-servlet(2.0)在每個HTTP請求的開始處注入數據庫連接,但是如何才能找出請求何時結束以便我可以關閉連接?清理@RequestScoped對象?

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

回答

5

這在Guice 2.0中是不可能的。一種解決方法是在每個請求結束時註冊一個自定義servlet偵聽器,以關閉連接:

/** 
* 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

吉斯默認不支持這一點,但可能我answer另一個問題可以幫助你得到的東西去。