【发布时间】:2018-05-31 11:10:28
【问题描述】:
我正在尝试使用 guice,我想在 Java Play 2.6 中创建一个单例随机 Web 服务客户端
现在我有我的 WS 客户端,它作为 java 播放模块加载。当我运行应用程序时,没问题,我的客户端能够使用注入的 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]
我很确定这里有一些问题,那么绑定然后使用它的正确方法是什么?
【问题讨论】:
标签: java dependency-injection playframework guice