【问题标题】:Guice Binding from Consumer Package消费包中的 Guice 绑定
【发布时间】:2017-11-04 14:16:34
【问题描述】:

我是 Guice 的新手,正在为以下用例寻求帮助:

我开发了一个包(PCKG),其中该包的入口类依赖于其他类,例如:

A : Entry point class --> @Inject A(B b) {}
B in turn is dependent on C and D like --> @Inject B(C c, D d) {}

在我正在做的绑定模块中:

bind(BInterface).to(Bimpl);
bind(CInterface).to(CImpl);
...

注意我没有为 A 提供绑定信息,因为我想通过它的消费者类来提供它的绑定。 (这就是设计的方式,所以我的要求是继续讨论主要问题而不是设计)。

现在我的消费者类正在做这样的事情:

AModule extends PrivateModule {
    protected void configure() {
        bind(AInterface.class).annotatedWith(AImpl.class);
    }
}

也在我的消费包中:

.(new PCKGModule(), new AModule())

第一季度。我在消费类中正确地进行绑定吗?我很困惑,因为当我在我的消费者包中进行如下内部测试时:

class testModule {
    bind(BInterface).to(Bimpl); 
    bind(CInterface).to(CImpl)... 
}

class TestApp {
    public static void main(..) {
        Guice.createInstance(new testModule());
        Injector inj = Guice.createInstance(new AModule());
        A obj = inj.getInstance(A.class);
    }
}

它正在抛出 Guice 创建异常。请帮助我摆脱这种情况。 我的一位对 Guice 也很幼稚的朋友也建议我需要使用提供注释在 AModule 中创建 B 的实例。但我真的没明白他的意思。

【问题讨论】:

    标签: dependency-injection guice


    【解决方案1】:

    你的主要方法应该是这样的:

    class TestApp {
    public static void main(..) {
        Injector injector = Guice.createInjector(new TestModule(), new AModule());
        A obj = injector.getInstance(A.class);
    }
    

    请注意,Java 约定是类名的首字母大写。

    我很确定您对 AModule 的实现也没有按照您的想法执行,但是根据您提供的信息很难确定。很可能,您的意思是这样做:

    bind(AInterface.class).to(AImpl.class)`
    

    没有必要对A 的绑定做任何“特殊”的事情。 Guice 为您解决所有递归问题。这是它“魔法”的一部分。

    annotatedWith()to()toInstance()一起使用,像这样:

    bind(AInterface.class).to(AImpl.class).annotatedWIth(Foo.class);
    bind(AInterface.class).to(ZImpl.class).annotatedWIth(Bar.class);
    

    然后你可以通过注解你的注入点来注入不同的实现,例如:

    @Inject
    MyInjectionPoint(@Foo AInterface getsAImpl, @Bar AInterface getsZImpl) {
        ....
    }
    

    还值得指出的是,您可以通过不打扰绑定模块(取决于您的代码的排列方式)并使用 JIT 绑定来潜在地为自己节省一些样板代码:

    @ImplementedBy(AImpl.class)
    public interface AInterface {
        ....
    }
    

    这些有效地充当“默认值”,被显式绑定(如果存在)覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 2018-04-25
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多