我有一个资源对象库:
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
。