[英]Properly adding Jest to Java Play 2.5.x
我试图了解如何最好地添加像 Jest to Play 这样的东西。
在 Play 的 2.5.x 依赖注入文档中,他们展示了如何添加单例,然后可以在需要时通过构造函数注入进行注入。
虽然这对我编写的类非常有意义,但我真的不明白如何注入像 Jest 这样的东西,它是通过工厂实例化的:
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://localhost:9200")
.multiThreaded(true)
//Per default this implementation will create no more than 2 concurrent connections per given route
.defaultMaxTotalConnectionPerRoute(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_PER_ROUTE>)
// and no more 20 connections in total
.maxTotalConnection(<YOUR_DESIRED_LEVEL_OF_CONCURRENCY_TOTAL>)
.build());
JestClient client = factory.getObject();
在我的控制器中,我应该如何正确注入 Jest? 我是否创建了一个开玩笑的工厂包装器,然后在构造函数中调用getObject()
? 这似乎根本不是一个理想的解决方案。
JestFactoryWrapper.java
@Singleton
class JestFactoryWrapper {
private JestFactory jestFactory;
JestFactoryWrapper() {
this.jestFactory = ...
}
public JestFactory getObject() {
return this.jestFactory.getObject()
}
}
接口控制器.java
@Inject
ApiController(JestFactoryWrapper jestFactory) {
this.jestClient = factory.getObject();
}
从文档:
JestClient
被设计为单例,不要为每个请求构造它!
https://github.com/searchbox-io/Jest/tree/master/jest
所以注入工厂并不是一个好的选择。
我想最好由工厂创建一个JestClient
并将类绑定到实例:
例子
模块:
public class Module extends AbstractModule {
@Override
protected void configure() {
...
bind(JestClient.class).toInstance(jestFactory.getObject());
...
}
}
用法:
@Inject
ApiController(JestClient jestClient) {
this.jestClient = jestClient;
}
创建一个提供者单例。
@Singleton
public class JestClientProvider implements Provider<JestClient> {
private final JestClient client;
@Inject
public JestClientProvider(final Configuration configuration, final ApplicationLifecycle lifecycle) {
// Read the configuration.
// Do things on the start of the application.
...
client = jestFactory.getObject();
lifecycle.addStopHook(() -> {
// Do things on the stop of the application.
// Close the connections and so on.
})
}
@Override
public JestClient get() {
return client;
}
}
在模块中绑定:
bind(JestClient.class).toProvider(JestClientProvider.class).asEagerSingleton();
用它:
@Inject
ApiController(JestClient jestClient) {
this.jestClient = jestClient;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.