java - 如何使用 Guice 设置同一个对象图的多个配置?

标签 java guice

您将如何构建下图中所示的对象图?

用户对象必须结合来自两个数据库后端的信息。

Multiple configurations of the same object graph

最佳答案

我找到了一个使用私有(private)模块的解决方案。

static class Service {
    @Inject Dao daoA;

    public void doSomething() {
        daoA.doA();
    }
}

static class Dao {
    @Inject DataSource dataSource;

    public void doA() {
        dataSource.execute();
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Connection {}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface X {}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Y {}

static class DataSource {
    @Connection @Inject String connection;

    public void execute() {
        System.out.println("execute on: " + connection);
    }
}

static class XServiceModule extends PrivateModule {
    @Override
    protected void configure() {
        bind(Service.class).annotatedWith(X.class).to(Service.class);
        expose(Service.class).annotatedWith(X.class);

        bindConstant().annotatedWith(Connection.class).to("http://server1");
    }
}

static class YServiceModule extends PrivateModule {
    @Override
    protected void configure() {
        bind(Service.class).annotatedWith(Y.class).to(Service.class);
        expose(Service.class).annotatedWith(Y.class);

        bindConstant().annotatedWith(Connection.class).to("http://server2");
    }
}

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new XServiceModule(), new YServiceModule()); 

    Service serviceX = injector.getInstance(Key.get(Service.class, X.class));  
    serviceX.doSomething(); 

    Service serviceY = injector.getInstance(Key.get(Service.class, Y.class));
    serviceY.doSomething(); 
}
  • Service 类的不同实例可以通过 X 和 Y 注释来标识。
  • 通过在私有(private)模块中隐藏所有其他依赖项,Dao 和 DataSource 之间没有冲突
  • 在两个私有(private)模块中,可以用两种不同的方式绑定(bind)常量
  • 服务通过 expose 暴露。

关于java - 如何使用 Guice 设置同一个对象图的多个配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10571609/

相关文章:

java - 何时何地使用 Guice 依赖注入(inject)?

Java构造函数模式

java - 基于命令行参数交换 Guice 绑定(bind)的最佳方法

java - 流行/标准 Java 库中是否有一个用于延迟计算值的类?

Java android - uplaud apk 和 google play 安全警报

java - Java中的条形码生成

java - Ivy 使用 Maven 快照 "revision already resolved"

java - Guice 注入(inject)通用列表

java - 捕获客户端上的休息异常

java - Access-Control-Allow-Origin 不允许来源 - 如何使用非常简单的 Web 堆栈和 guice 启用 CORS