我怎样才能让Gu​​ice在jar中管理一个类(如果可能的话)?

时间:2012-07-24 05:48:46

标签: java dependency-injection guice

假设我在类路径中的jar中有一个A类(即,我无法控制其来源,因此不能简单地用@Inject注释它)。 A具有以下构造函数定义:

A(B b, C c) {
    this.b = b;
    this.c = c;
}

在我的代码库中,我有类:

BImpl implements B

CImpl implements C

我的问题是:如何配置Guice来管理要注入BImpl和CImpl的A实例(如果它甚至在框架范围内)?

1 个答案:

答案 0 :(得分:1)

当你说“jar文件中的A类”时,我假设你无法控制该类的来源 - 你不能简单地将@Inject添加到构造函数中。

如果是这种情况,那么您可以像这样定义Module

class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(B.class).to(BImpl.class);
        bind(C.class).to(CImpl.class);

        try {
            bind(A.class).toConstructor(A.class.getConstructor(B.class, C.class));
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}

前两个绑定是标准的 - 您将接口类型绑定到实现类型。

最后一个绑定使用toConstructor(自Guice 3.0开始),它允许您更容易地“粘合”外部组件 - 就像您的情况一样。