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