[英]Spring define a request scoped bean that has access to the request object
[英]Spring - Request scoped bean from object pool
我有一個資源對象庫:
public interface PooledResource {
...
}
@Component
public class ResourcePool {
public PooledResource take() { ... }
public void give(final PooledResource resource) { ... }
}
當前,我在JAX-RS端點中按以下方式使用此池:
@Path("test")
public class TestController {
@Autowired
private ResourcePool pool;
@GET
Response get() {
final PooledResource resource = pool.take();
try {
...
}
finally {
pool.give(resource);
}
}
}
這很好。 但是,手動請求PooledResource
並被迫不要忘記finally
子句使我感到緊張。 我想按以下方式實現控制器:
@Path("test")
public class TestController {
@Autowired
private PooledResource resource;
@GET
Response get() {
...
}
}
在這里,注入PooledResource
而不是管理池。 此注入應在請求范圍內進行,並且在請求完成之后,必須將資源分配回池中。 這很重要,否則最終我們將耗盡資源。
春天有可能嗎? 我一直在玩FactoryBean
,但這似乎不支持退還bean。
實現HandlerInterceptor
並將其注入到請求范圍的Bean中。 調用preHandle
,使用正確的值設置bean。 afterCompletion
后,請再次對其進行清理。
請注意,您需要將其與Bean Factory結合使用,以將PooledResource
注入到其他組件中。
工廠基本上會注入與HandlerInterceptor
使用的對象相同的對象,並創建(或僅返回) PooledResource
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.