簡體   English   中英

如何在Java Play中使用Guice創建和使用實例

[英]How to create and use and instance using guice in java play

我正在嘗試使用guice,並且想在Java Play 2.6中創建一個Singleton隨機Web服務客戶端。

現在,我有我的WS客戶端,它將作為Java Play模塊加載。 當我運行該應用程序時,沒問題,我的客戶端能夠使用注入的java play配置( com.typesafe.config.Config )。 但是,如果我嘗試在其他任何地方使用我的客戶端,則會收到一條錯誤消息No implementation for com.typesafe.config.Config was bound

這是我的客戶(非常簡單):

import play.Logger;
import com.typesafe.config.Config;

@Singleton
public class MyClient {
    final Config config;

    @Inject
    public MyClient(Config config) {
        this.config = config;
        Logger.warn("constructor called")
        Logger.warn("Some config param:"+config.getString("some_param"))
    }

    public void doSomething() {
        Logger.warn("doSomething() called")
    }

}

我的模塊實現Guice的AbstractModule:

import com.google.inject.AbstractModule;

public class MyClientModule extends AbstractModule {
    @Override 
    protected void configure() {
        bind(MyClient.class).asEagerSingleton();
    }

}

當我告訴Play將它用作applicationf.conf的模塊時,它可以工作(我在控制台中獲得了"Constructor called""Some config param"警告日志):

play {
  modules {
    enabled += external.MyClientModule
  }
}

但是,如果我嘗試從HomeController調用它:

public class HomeController extends Controller {
    public Result index() {
        Injector myClientInjector = Guice.createInjector(new MyClientModule());
        MyClient myClient = myClientInjector.getInstance(MyClient.class);
        return ok(views.html.index.render());
    }
}

然后我得到以下錯誤:

[CreationException: Unable to create injector, see the following errors:

1) No implementation for com.typesafe.config.Config was bound.
  while locating com.typesafe.config.Config
    for the 1st parameter of external.MyClient.<init>(MyClient.java:121)
  at external.MyClientModule.configure(MyClientModule.java:8)

1 error]

我敢肯定這里有一些錯誤,那么綁定它然后使用它的正確方法是什么?

asEagerSingleton()綁定意味着它的綁定速度盡可能快。 在這種情況下,Config尚未綁定,因此將失敗。

采用

bind(MyClient.class).in(Singleton.class)

需要時將其綁定為單例。

在HomeController中,使用構造函數注入:

@Inject
public HomeController (final MyClient myclient) {
    this.myclient = myclient;
}

您可以像這樣注釋1個構造函數,因此它需要包含要注入的所有類。 您可以將構造函數和字段注入結合使用,但是不建議這樣做。

在HomeController中,使用構造函數注入:

@Inject
public HomeController (final MyClient myclient) {
    this.myclient = myclient;
}

您可以像這樣注釋1個構造函數,因此它需要包含要注入的所有類。 您可以將構造函數和字段注入結合使用,但是不建議這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM