Guice的新手,所以我正在研究它的表现力。假设我有以下课程:
public class Data {
@Inject
public Data(@Named("First") String first, @Named("Second") String second) { ... }
}
public class DataUser1 {
@Inject
public DataUser1(Data data) { ... }
}
public class DataUser2 {
@Inject
public DataUser2(Data data) { ... }
}
如何创建一个模块,以便在我调用injector.getInstance(DataUser1.class)
时获得与new DataUser1(new Data("foo", "bar"))
同等的内容injector.getInstance(DataUser2.class)
我得到的内容等同于new DataUser2(new Data("foo2", "bar2"))
?
另外,我如何创建一个模块,我可能需要获取两个DataUser1
个实例,每个实例使用不同的Data
值?
答案 0 :(得分:1)
您使用private modules创建几乎相同但具体细节不同的对象图。
public class DataUser1Module extends PrivateModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("First")).to("foo");
bindConstant().annotatedWith(Names.named("Second")).to("bar");
bind(Data.class);
bind(DataUser1.class);
expose(DataUser1.class);
}
}
public class DataUser2Module extends PrivateModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("First")).to("foo2");
bindConstant().annotatedWith(Names.named("Second")).to("bar2");
bind(Data.class);
bind(DataUser2.class);
expose(DataUser2.class);
}
}
Injector injector = Guice.createInjector(new DataUser1Module(), new DataUser2Module());
DataUser1 dataUser1 = injector.getInstance(DataUser1.class);
DataUser2 dataUser2 = injector.getInstance(DataUser2.class);
如果您需要两个DataUser1
具有不同Data
的实例,则会执行相同的操作,但您使用注释来区分它们:
public class DataUser1Module1 extends PrivateModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("First")).to("foo");
bindConstant().annotatedWith(Names.named("Second")).to("bar");
bind(Data.class);
bind(DataUser1.class).annotatedWith(Names.named("1")).to(DataUser1.class);
expose(DataUser1.class).annotatedWith(Names.named("1"));
}
}
public class DataUser1Module2 extends PrivateModule {
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("First")).to("foo2");
bindConstant().annotatedWith(Names.named("Second")).to("bar2");
bind(Data.class);
bind(DataUser1.class).annotatedWith(Names.named("2")).to(DataUser1.class);
expose(DataUser1.class).annotatedWith(Names.named("2"));
}
}
Injector injector = Guice.createInjector(new DataUser1Module1(), new DataUser1Module2());
DataUser1 dataUser11 = injector.getInstance(Key.get(DataUser1.class, Names.named("1"));
DataUser1 dataUser12 = injector.getInstance(Key.get(DataUser1.class, Names.named("2"));
此模式在Guice常见问题解答中为described。
另见这些问题: