假设我有两个相似(但不同)的方法(或者可能是静态方法)create_x()
和create_y()
来创建对象(称它们为x
和y
),两者都是Parser
类的派生类。
现在我想绑定(bind)这两种方法创建的对象,如 answer to my previous question 所示:
bind(Parser.class)
.annotatedWith(Names.named("x"))
.to(ParserXImplementation.class);
bind(Parser.class)
.annotatedWith(Names.named("y"))
.to(ParserYImplementation.class);
但使用 create_x()
、create_y()
创建的对象,而不是 ParserXImplementation
、ParserYImplementation
类的实例。 (因此无需创建类 ParserXImplementation
、ParserYImplementation
。)
请注意,我希望对象是单例。
我想要针对 create_x()
、create_y()
是静态方法的情况以及它们是实例方法的情况的答案。如果它们是实例方法,则包含它们的类本身可能会受到依赖注入(inject)。
如何做到这一点? (将依赖项注入(inject)到方法创建的实例中)
最佳答案
来自https://github.com/google/guice/wiki/ProvidesMethods :
当您需要代码来创建对象时,请使用@Provides
方法。该方法必须在模块内定义,并且必须具有 @Provides
注释。该方法的返回类型是绑定(bind)类型。每当注入(inject)器需要该类型的实例时,它将调用该方法。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
...
}
@Provides
TransactionLog provideTransactionLog() {
DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
transactionLog.setThreadPoolSize(30);
return transactionLog;
}
}
此外,它还表示可以使用 @Named("x")
和 @Named("y")
等注释来区分 x
和 y
,如 Binding the same interface twice (Guice) 的答案中所述。 .
这就是我所需要的(但是该方法是在模块内部定义的,而不是在任意类中定义的)。
关于java - Guice:通过方法创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47839235/