如何使用Guice的AssistedInject?

97

相关的,下面的答案没有涵盖同一类型被多次使用的情况。https://dev59.com/0GAg5IYBdhLWcg3wdq0y - Alexander Oh
1个回答

203

请查看FactoryModuleBuilder类的Javadoc文档。

AssistedInject允许您动态配置Factory类,而无需自己编写代码。当您有一个对象具有应注入的依赖项和必须在创建对象时指定的某些参数时,这通常很有用。

示例文档中给出了一个RealPayment示例。

public class RealPayment implements Payment {
   @Inject
   public RealPayment(
      CreditService creditService,
      AuthService authService,
      @Assisted Date startDate,
      @Assisted Money amount) {
     ...
   }
 }

注意,CreditServiceAuthService必须通过容器注入,但是startDateamount应该由开发人员在实例创建期间指定。

因此,您不是注入一个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);

9
非常感谢您的寻找,但我未能找到更为简洁和清晰的解释来解决我的疑问。 - Gabber
23
比起 Github 上的文档,这个更易懂了。做得好。 - arjabbar
9
与此相比,Github 的文档不如这个好。 - EMM
2
“date”和“amount”不应该在调用“Payment”方法时传递吗?为什么它们应该在构造函数中注入? - Harshit
5
对于那些想知道的人,RealPayment不需要实现一个接口。 - jsallaberry
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接