程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用Guice将参数传递给构造函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用Guice将参数传递给构造函数?

开发过程中遇到使用Guice将参数传递给构造函数的问题如何解决?下面主要结合日常开发的经验,给出你关于使用Guice将参数传递给构造函数的解决方法建议,希望对你解决使用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!"
    }
}
这里有很多帮助:[https](https://google.github.io/guice/api-
docs/latest/javadoc/index.HTML?com/Google/inject/assistedinject/FactoryModuleBuilder.HTML)
//google.github.io/guice/api- docs/latest/javadoc/index.html?com/ Google/inject/assistedinject/FactoryModuleBuilder.html

解决方法

我的工厂如下

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,请注明来意。
标签: