91

我已经阅读了https://github.com/google/guice/wiki/AssistedInject,但它没有说明如何传递 AssistedInject 参数的值。injector.getInstance() 调用会是什么样子?

4

1 回答 1

189

检查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您不是注入 a 而是注入PaymentFactory带有标记为@Assisted的参数的 aRealPayment

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);
于 2012-01-23T21:51:52.727 回答