正确地将Jest添加到Java Play 2.5.x.

时间:2017-05-03 07:29:04

标签: java dependency-injection playframework jest

我正在努力了解如何最好地添加像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?我是否创建了一个jest工厂包装器,然后在构造函数中调用getObject()?它似乎不是一个理想的解决方案。

JestFactoryWrapper.java

@Singleton
class JestFactoryWrapper {

    private JestFactory jestFactory;

    JestFactoryWrapper() {
        this.jestFactory = ...
    }

    public JestFactory getObject() {
        return this.jestFactory.getObject()
    }
}

ApiController.java

@Inject
ApiController(JestFactoryWrapper jestFactory) {
    this.jestClient = factory.getObject();
}

1 个答案:

答案 0 :(得分:1)

来自文档:

  

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;
}

<强> Provider Bindings

创建提供者单例。

@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;
}