栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Guice将参数传递给构造函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/428047.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号