使用 Guice 将参数传递给构造函数 [英] Pass parameter to constructor with Guice
问题描述
我有一个工厂如下,
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 的定义:
This is the Foo definition:
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 and a visual:
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
public String getFooName() {
return this.bar;
}
}
//使用仅接受辅助参数的 create() 方法创建工厂接口.
// Create a factory interface with a create() method that takes only the assisted parameters.
//FooFactory 接口没有明确的实现类(Guice Magic)
// 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
class BinderModule implements Module {
public void configure(Binder binder) {
binder.install(new FactoryModuleBuilder()
.implement(FooInterface.class, Foo.class)
.build(FooFactory.class));
}
}
//现在使用它:
class FooAction {
@Inject private FooFactory fooFactory;
public String doFoo() {
// Send bar details through the Factory, not the "injector"
Foo f = fooFactory.create("This foo is named bar. How lovely!");
return f.getFooName(); // "This foo is named bar. How lovely!"
}
}
这篇关于使用 Guice 将参数传递给构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!