我有一个工厂如下,
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 构造函数?
有任何想法吗?
原文由 DarthVader 发布,翻译遵循 CC BY-SA 4.0 许可协议
所有“Guice Constructor Parameter”答案在某种程度上似乎都不完整。这是一个完整的解决方案,包括用法和视觉效果:
// 在实现类上注解构造函数和辅助参数
// 使用仅采用辅助参数的 create() 方法创建工厂接口。
// FooFactory 接口没有明确的实现类 (Guice Magic)
// 将该工厂绑定到由 AssistedInject 创建的提供者
// 现在使用它:
这里有很多帮助: https ://google.github.io/guice/api-docs/latest/javadoc/index.html?com/google/inject/assistedinject/FactoryModuleBuilder.html