大佬教程收集整理的这篇文章主要介绍了使用Guice将参数传递给构造函数,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
所有“ Guice构造函数参数”答案在某种程度上似乎都不完整。这是一个完整的解决方案,包括用法:
interface FooInterface {
String getFooname();
}
//在实现类上注释构造函数和辅助参数
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()方法创建工厂接口。
// FooFactory接口没有显式的实现类(Guice Magic)
interface FooFactory {
Foo create(String bar);
}
//将该工厂绑定到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!"
}
}
我的工厂如下
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构造函数?
有任何想法吗?
以上是大佬教程为你收集整理的使用Guice将参数传递给构造函数全部内容,希望文章能够帮你解决使用Guice将参数传递给构造函数所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。