使用Guice将参数传递给构造函数 [英] Pass parameter to constructor with Guice
问题描述
我有一个工厂,如下所示,
I have a factory as below,
public final class Application {
private static IFoo foo;
public static IFoo getFoo(String bar)
{
// i need to inject bar to the constructor of Foo
// obvious i have to do something, not sure what
Injector injector = Guice.createInjector();
logger = injector.getInstance(Foo.class);
return logger;
}
}
这是Foo的定义:
class Foo
{
Foo(String bar)
{
}
}
好的。我不确定如何使用Guice将此参数传递给Foo构造函数?
OK. I m not sure how I can pass this parameter to Foo constructor with Guice?
任何想法?
推荐答案
所有Guice构造函数参数的答案在某种程度上似乎都是不完整的。
这是一个完整的解决方案,包括用法:
All the "Guice Constructor Parameter" answers seem to be incomplete in some way. Here is a complete solution, including usage:
interface FooInterface{
String getFooName();
}
//在实现类上注释构造函数和辅助参数
// Annotate the constructor and assisted parameters on the implementation class
class Foo implements FooInterface {
String bar;
@Inject
Foo(@Assisted String bar)
{
this.bar = bar;
}
// return the final name
getFooName(){
return this.bar;
}
}
//创建工厂界面一个create()方法,只接受辅助参数。
// FooFactory接口没有显式的实现类(Guice Magic)
// Create a factory interface with a create() method that takes only the assisted parameters. // FooFactory interface doesn't have an explicit implementation class (Guice Magic)
interface FooFactory{
Foo create(String bar);
}
//将该工厂绑定到由AssistedInject创建的提供商
// Bind that factory to a provider created by AssistedInject
binderModule implements Module{
void configure(Binder binder) {
binder.install(new FactoryModuleBuilder()
.implement(FooInterface.class, Foo.class)
.build(FooFactory.class));
}
}
//现在使用它:
class FooAction{
@Inject private FooFactory fooFactory;
doFoo(){
// Send bar details through the Factory, not the "injector"
Foo f = fooFactory.create("This foo is named bar. How lovely!");
f.getFooName(); // "This foo is named bar. How lovely!"
}
}
这篇关于使用Guice将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!