如何使用Guice的AssistedInject? [英] How to use Guice's AssistedInject?

查看:783
本文介绍了如何使用Guice的AssistedInject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've read https://github.com/google/guice/wiki/AssistedInject, but it doesn't say how to pass in the values of the AssistedInject arguments. What would the injector.getInstance() call look like?

推荐答案

检查 FactoryModuleBuilder 类。

AssistedInject 允许您为类动态配置 Factory 而不是编码你自己。当您有一个具有应该注入的依赖项的对象以及在创建对象期间必须指定的一些参数时,这通常很有用。

AssistedInject allows you to dynamically configure Factory for class instead of coding it by yourself. This is often useful when you have an object that has a dependencies that should be injected and some parameters that must be specified during creation of object.

文档中的示例是 RealPayment

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

查看 CreditService AuthService 应该由容器注入,但startDate和amount应该由开发人员在实例创建期间指定。

See that CreditService and AuthService should be injected by container but startDate and amount should be specified by a developer during the instance creation.

所以不是注入 Payment 而是注入 PaymentFactory ,其参数标记为 @Assisted in RealPayment

So instead of injecting a Payment you are injecting a PaymentFactory with parameters that are marked as @Assisted in RealPayment

public interface PaymentFactory {
    Payment create(Date startDate, Money amount);
}

工厂应绑定

install(new FactoryModuleBuilder()
     .implement(Payment.class, RealPayment.class)
     .build(PaymentFactory.class));

可以在您的班级注入配置的工厂。

Configured factory can be injected in your classes.

@Inject
PaymentFactory paymentFactory;

并在您的代码中使用

Payment payment = paymentFactory.create(today, price);

这篇关于如何使用Guice的AssistedInject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆