[英]Spring - Request scoped bean from object pool
I have an object pool of resources: 我有一个资源对象库:
public interface PooledResource {
...
}
@Component
public class ResourcePool {
public PooledResource take() { ... }
public void give(final PooledResource resource) { ... }
}
Currently, I am using this pool as following in my JAX-RS endpoints: 当前,我在JAX-RS端点中按以下方式使用此池:
@Path("test")
public class TestController {
@Autowired
private ResourcePool pool;
@GET
Response get() {
final PooledResource resource = pool.take();
try {
...
}
finally {
pool.give(resource);
}
}
} }
This works fine. 这很好。 However, requesting the PooledResource
manually and being forced to not forget the finally
clause makes me nervous. 但是,手动请求PooledResource
并被迫不要忘记finally
子句使我感到紧张。 I would like to implement the controller as following: 我想按以下方式实现控制器:
@Path("test")
public class TestController {
@Autowired
private PooledResource resource;
@GET
Response get() {
...
}
} }
Here, the PooledResource
is injected, instead of the managing pool. 在这里,注入PooledResource
而不是管理池。 This injection should be request scoped, and also, after finalization of the request, the resource must be given back to the pool. 此注入应在请求范围内进行,并且在请求完成之后,必须将资源分配回池中。 This is important, or we will run out of resources eventually. 这很重要,否则最终我们将耗尽资源。
Is this possible in Spring? 春天有可能吗? I have been playing with FactoryBean
, but this does not seem to support to give back the bean. 我一直在玩FactoryBean
,但这似乎不支持退还bean。
Implement a HandlerInterceptor
and inject it with a request scoped bean. 实现HandlerInterceptor
并将其注入到请求范围的Bean中。 When preHandle
is called, setup the bean with the correct value. 调用preHandle
,使用正确的值设置bean。 When afterCompletion
is called, clean it up again. afterCompletion
后,请再次对其进行清理。
Note that you will need to combine this with a Bean Factory to get a nice PooledResource
injection into your other components. 请注意,您需要将其与Bean Factory结合使用,以将PooledResource
注入到其他组件中。
The Factory basically injects the same object as you used in the HandlerInterceptor
and creates (or just returns) a PooledResource
. 工厂基本上会注入与HandlerInterceptor
使用的对象相同的对象,并创建(或仅返回) PooledResource
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.