代码之家  ›  专栏  ›  技术社区  ›  Prashant

来自消费者软件包的Guice绑定

  •  0
  • Prashant  · 技术社区  · 8 年前

    我是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);
    ...
    

    注意,我没有为提供绑定信息,因为我希望通过其使用者类提供其绑定。(这就是设计的方式,所以我的要求是继续讨论主要问题,而不是设计)。

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

    在我的消费者套餐中:

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

    问题1.我在consumer类中正确地进行了绑定吗。我很困惑,因为当我在我的消费者软件包中进行以下内部测试时:

    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的实例。但我真的没有领会他的意思。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Graham    8 年前

    您的主要方法如下所示:

    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 {
        ....
    }
    

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