gpt4 book ai didi

java - Guice 指定用于注入(inject)的模块

转载 作者:行者123 更新时间:2023-11-30 07:11:33 25 4
gpt4 key购买 nike

在我的应用程序中,有多个模块将某些内容绑定(bind)到特定名称或类。有没有办法告诉 Guice,在解析要注入(inject)的依赖项时应该使用哪些模块。

我的简化依赖关系图看起来像这样,其中蓝色表示来自模块 1 的类,红色表示来自模块 2 的类。现在我想从 A 类创建两个实例,但不同的类绑定(bind)到某些依赖项.

Dependencies

public class Module1 extends AbstractModule {
@Override
protected void configure() {
bind(C.class).to(C_Impl1.class)
bind(D.class).to(D_Impl1.class)
}
}


public class Module2 extends AbstractModule {
@Override
protected void configure() {
bind(C.class).to(C_Impl2.class)
bind(D.class).to(D_Impl2.class)
}
}

public class Application {
@Inject @UseModules(Module1, ...) private final A someClassUsingImpl1;
@Inject @UseModules(Module2, ...) private final A someClassUsingImpl2;

public void doSomethingWithImpl1() {
someClassUsingImpl1.doSomething()
}

public void doSomethingWithImpl2() {
someClassUsingImpl2.doSomething()
}
}

最佳答案

这就是问题private modules是为.您仍然需要使用绑定(bind)注释来区分您是否要求 Impl1 A 的版本或Impl2 A 的版本.

/** Marks Impl1 classes. Inject @Impl1 A to get A using C_Impl1 and D_Impl1. */
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@interface Impl1 {}

/** Marks Impl2 classes. Inject @Impl2 A to get A using C_Impl2 and D_Impl2. */
@BindingAnnotation
@Retention(RetentionPolicy.RUNTIME)
@interface Impl2 {}

/** This is now a PrivateModule. Only exposed bindings can be used outside. */
public class Module1 extends PrivateModule {
@Override
protected void configure() {
// Bind C and D as you had before.
bind(C.class).to(C_Impl1.class);
bind(D.class).to(D_Impl1.class);
// Here's the tricky part: You're binding "@Impl1 A" to
// "A" without a binding annotation, but only in here.
bind(A.class).annotatedWith(Impl1.class).to(A.class);
// Now you expose @Impl1 A, so it can be used outside.
// As long as A, C, and D are only bound within private modules,
// they won't conflict with one another, and @Impl1 A is unique.
expose(A.class).annotatedWith(Impl1.class);
}
}

/** Treat Module2 the same way, as a private module. */

public class Application {
@Inject @Impl1 private final A someClassUsingImpl1;
@Inject @Impl2 private final A someClassUsingImpl2;
// ...
}

如果这对您来说是常见模式,请创建一个通用 PrivateModule,它接受不同的类作为构造函数参数,这样您就不需要重复自己。这些可以添加到顶级注入(inject)器,或 installed within other modules .

Injector injector = Guice.createInjector(new YourMainModule(),
new ImplModule(Impl1.class, C_Impl1.class, D_Impl1.class),
new ImplModule(Impl2.class, C_Impl2.class, D_Impl2.class));

关于java - Guice 指定用于注入(inject)的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39161497/

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