我有一个使用Guice的自定义提供程序,下面有一些伪代码:
public class MyProvider implements Provider<String> {
public String get() {
System.out.println("Called MyProvider.get()");
return "abcd";
}
}
public class MyModule extends AbstractModule {
protected void configure() {
bind(String.class).toProvider(MyProvider.class);
}
}
public class MyManager {
private MyProvider<String> myProvider;
@Inject
public MyManager(Provider<String> myProvider) { this.myProvider = myProvider; }
}
有一个MyManager对象代表我们将来在Guice连接后要构建的内容。现在为了真正开始这个,我有点失落......
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MyModule());
// not sure what to do here. This doesn't work but I thought it'd be something like this
MyManager mgr = new MyManager(injector.getProvider(MyProvider.class));
}
答案 0 :(得分:3)
我不确定这是否是“首选方式”,但这似乎有效:
Injector injector = Guice.createInjector(new MyModule());
MyManager mgr = injector.getInstance(MyManager.class);
如果这是做到这一点的想法?
答案 1 :(得分:0)
来自Injector的JavaDoc:
返回用于获取给定类型实例的提供程序。
听起来你需要传递返回的提供者将提供的对象的类。由于您需要返回String的提供程序,我认为您需要传递String.class
。
试试这个:
public static void main(String[] args) {
Injector injector = Guice.createInjector(new MyModule());
MyManager mgr = new MyManager(injector.getProvider(String.class));
}