繁体   English   中英

Spring-从对象池请求作用域的Bean

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM