我已经阅读了https://github.com/google/guice/wiki/AssistedInject,但是它没有说明如何传递AssistedInject参数的值。那么 injector.getInstance() 的调用应该是什么样子的呢?
我已经阅读了https://github.com/google/guice/wiki/AssistedInject,但是它没有说明如何传递AssistedInject参数的值。那么 injector.getInstance() 的调用应该是什么样子的呢?
请查看FactoryModuleBuilder类的Javadoc文档。
AssistedInject
允许您动态配置Factory
类,而无需自己编写代码。当您有一个对象具有应注入的依赖项和必须在创建对象时指定的某些参数时,这通常很有用。
示例文档中给出了一个RealPayment
示例。
public class RealPayment implements Payment {
@Inject
public RealPayment(
CreditService creditService,
AuthService authService,
@Assisted Date startDate,
@Assisted Money amount) {
...
}
}
注意,CreditService
和AuthService
必须通过容器注入,但是startDate
和amount
应该由开发人员在实例创建期间指定。
因此,您不是注入一个Payment
,而是注入一个带有在RealPayment
中标记为@Assisted
的参数的PaymentFactory
。
public interface PaymentFactory {
Payment create(Date startDate, Money amount);
}
应该绑定一个工厂。
install(new FactoryModuleBuilder()
.implement(Payment.class, RealPayment.class)
.build(PaymentFactory.class));
配置好的工厂可以注入到你的类中。
@Inject
PaymentFactory paymentFactory;
并在你的代码中使用
Payment payment = paymentFactory.create(today, price);
RealPayment
不需要实现一个接口。 - jsallaberry