gpt4 book ai didi

java - Guice - 基于封闭类绑定(bind)不同的实例

转载 作者:行者123 更新时间:2023-12-01 13:31:13 25 4
gpt4 key购买 nike

是否可以根据封闭类绑定(bind)命名实例?例如:在下面的示例中,类 A 和 B 将获得注入(inject)的 DataStore 实例。但是,我需要在类 A 的范围/上下文中将主存储作为 StoreA,将辅助存储作为 StoreB,但在类 B 的范围/上下文中将主存储作为 StoreC,将辅助存储作为 StoreD。如何实现?

class A {
@Inject
public A(DataStore dataStore) {
...
}
}

class B {
@Inject
public B(DataStore dataStore) {
...
}
}

class DataStore {
@Inject
public A(@Named("primary") Store primaryStore, @Named("secondary") Store store) {
...
}
}

bind(Store.class).annotatedWith(Names.named("primary")).to(StoreA.class);//for class A
bind(Store.class).annotatedWith(Names.named("secondary")).to(StoreB.class);//for class A
bind(Store.class).annotatedWith(Names.named("primary")).to(StoreC.class);//for class B
bind(Store.class).annotatedWith(Names.named("secondary")).to(StoreD.class);//for class B

最佳答案

这有时称为 "robot legs" problem ,就像 build 一个具有相同腿但左右脚不同的机器人一样。每条腿绑定(bind)一个脚,但请求的脚取决于请求的腿。在您的情况下,每个 DataStore 都绑定(bind)到一个主 Store 和一个辅助 Store,但哪些 Store 取决于所请求的 DataStore。

Guice 注入(inject)的实例不能直接根据其目标( similar feature was rejected )进行绑定(bind),但是 as mentioned in the FAQ您可以使用PrivateModule创建类似的效果。

install(new PrivateModule() {
@Override public void configure() {
bind(Store.class).annotatedWith(Names.named("primary")).to(StoreA.class);
bind(Store.class).annotatedWith(Names.named("secondary")).to(StoreB.class);
expose(A.class);
}
});
install(new PrivateModule() {
@Override public void configure() {
bind(Store.class).annotatedWith(Names.named("primary")).to(StoreC.class);
bind(Store.class).annotatedWith(Names.named("secondary")).to(StoreD.class);
expose(B.class);
}
});

因此,@Named("primary") Store 将无法在 AB(或其依赖项)之外访问,但是这就说得通了;您永远不会定义通用的 Store,但是 AB 都有它们需要的私有(private)绑定(bind)。

(免责声明:我没有机会对此进行测试,因此可能需要改进。)

关于java - Guice - 基于封闭类绑定(bind)不同的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21554841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com