检查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你注入
PaymentFactory与被标记为参数
@Assisted的
RealPayment
public interface PaymentFactory { Payment create(Date startDate, Money amount);}
工厂应该被捆绑
install(new FactoryModuleBuilder() .implement(Payment.class, RealPayment.class) .build(PaymentFactory.class));
可以将配置好的工厂注入您的班级中。
@InjectPaymentFactory paymentFactory;
并在您的代码中使用
Payment payment = paymentFactory.create(today, price);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)