您将如何构建下图中所示的对象图?
用户对象必须结合来自两个数据库后端的信息。
最佳答案
我找到了一个使用私有(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/