我有一个资源对象库:

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

09-16 06:57