假设有一个类 A,它的构造函数看起来像这样:
public A(@Assited long id, @Assisten String name, ServiceA serviceA, ServiceB serviceB)
还有 AFactory:
public interface AFactory{
A create(long id, String name);
}
因此,要创建 A 的实例,我显然需要执行类似的操作:
injector = Guice.createInjector(new MyModule());
AFactory af = injector.getInstance(AFactory .class);
A a = AFactory.create(100, "mike");
但是, 假设我有其他类:例如,B 类、C 类和 D 类都有一个类型为 A 的成员(具有字段注入(inject),但也可以是 ctor):
public class B{
@Inject
A a;
}
我希望将 A 的相同实例注入(inject)到这些类中。 但仍然可以选择将 A 的另一个实例注入(inject)其他类(例如 E 类和 F 类)。
正确的做法是什么? 我只是想不出一个干净的方法来做到这一点。
最佳答案
您可以构建您的模块以使用提供程序(我正在使用下面的 @Provides 方法,但如果您愿意,您可以使用完整的提供程序类或实例),并将一致的 A 标记为 @Singleton 。如果想要 A 的两个绑定(bind)(一致和不一致),则至少其中之一应该使用绑定(bind)注释进行标记;出于方便起见,我在这里使用 @Named
,但您可以使用列出的任何绑定(bind)注释 in the docs .
public class AModule extends AbstractModule {
@Override public void configure() {
// Install your AFactory module. Here, injections for AFactory should succeed.
install(new FactoryModuleBuilder().build(AFactory.class));
}
/**
* Provides a singleton @Named("consistent") A.
* Inject @Named("consistent") A into B, C, and D; Guice will cache the instance.
*/
@Provides @Singleton @Named("consistent")
A provideConsistentA(AFactory factory) {
return factory.create(100, "mike");
}
/**
* Provides an unscoped A.
* Inject A without an annotation into E and F; each instance will be separate.
*/
@Provides @Singleton A provideUnscopedA(AFactory factory) {
return factory.create(200, "jeff");
}
}
关于java - Guice - 绑定(bind)由辅助注入(inject)工厂创建的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40512944/