【问题标题】:Add new binding to a Guice Module?向 Guice 模块添加新绑定?
【发布时间】:2017-05-31 16:52:24
【问题描述】:

我有自己的 Guice 模块,在 configure 方法中,我提供了自己的绑定,如下所示 -

public void configure() {
    MapBinder<String, ExternalDatabaseConnection> m = MapBinder.newMapBinder(binder(), String.class, ExternalDatabaseConnection.class);
    m.addBinding("DBServer1").to(ExternalDBServer1Connection.class);
    m.addBinding("DBServer2").to(ExternalDBServer2Connection.class);
}  

以上内容部署为 Web 应用程序。 我想让第三方提供商能够提供自己的实现并为连接类提供一个 jar 文件。我怎么做?这不是修改上面的代码以添加新的绑定,如下所示 -

m.addBinding("DBServer3").to(ExternalDBServer3Connection.class);

【问题讨论】:

  • 第三方代码已经能够做到这一点,只需安装您的模块,然后自己使用MapBinder

标签: java spring module guice inject


【解决方案1】:

您可以组合模块。这是一个例子。假设您有独立存在的外部和内部模块。

public class InternalModule extends AbstractModule {

    @Override
    protected void configure() {
        MapBinder<String, String> m = MapBinder.newMapBinder(binder(), String.class, String.class);
        m.addBinding("DBServer1").toInstance("Value1");
        m.addBinding("DBServer2").toInstance("Value2");
    }

}

和:

public class ExternalModule extends AbstractModule {

    @Override
    protected void configure() {
        MapBinder<String, String> m = MapBinder.newMapBinder(binder(), String.class, String.class);
        m.addBinding("DBServer3").toInstance("Value3");
    }

}

这是一个基于两个模块组合的注入器(例如,它可能存在于您的应用中,您可以实现一些简单的注册机制):

InternalModule moduleInt = new InternalModule();
ExternalModule moduleExt = new ExternalModule();

Module combined = Modules.combine(moduleInt, moduleExt);

Injector injector = Guice.createInjector(combined);

当这个注入器注入一个地图时,例如:

@Inject
private Map<String, String> stringMap;

此地图将包含以下值:

{DBServer1=Value1, DBServer2=Value2, DBServer3=Value3}

Javadoc of Modules.

也可以覆盖模块而不是组合它们。在这种情况下,外部库将替换您自己的实现。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    支持来自不同模块的映射绑定。

    查看this了解更多详情。

    【讨论】:

      猜你喜欢
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多