2017-05-03 2 views
1

JestのようなものをPlayに追加する方法を理解しようとしています。JestをJava Play 2.5.xに正しく追加する

Playの2.5.x依存性注入ドキュメントでは、シングルトンを追加する方法を示しています。シングルトンは、コンストラクタインジェクションによって必要なときに注入することができます。私のコントローラで

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

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

おかげで、このことができます。フォローアップとして、Module.javaで工場を初期化するか、それ自体を注入することができますか?私はguiceのベストプラクティスを探していましたが、これに関連するものは実際には見つかりませんでした。 – user490895

+0

私の答えの更新された「プロバイダバインディング」セクションを参照 –

関連する問題