gpt4 book ai didi

java - 清理 @RequestScoped 对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:15:15 26 4
gpt4 key购买 nike

我正在使用 guice-servlet (2.0) 在每个 HTTP 请求开始时注入(inject)一个数据库连接,但是我怎样才能知道请求何时结束以便关闭连接?

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

最佳答案

这在 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()
{
}
}

关于java - 清理 @RequestScoped 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4739264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com