如何使用 Guice 的 AssistedInject?

发布于 2024-12-28 18:26:53 字数 211 浏览 1 评论 0原文

我已阅读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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

楠木可依 2025-01-04 18:26:53

检查 FactoryModuleBuilder 类。

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

文档中的示例是 RealPayment

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

请参阅 CreditServiceAuthService 应由容器注入,但 startDate 和金额应由开发人员在开发过程中指定实例创建。

因此,您不是注入 Payment,而是注入 PaymentFactory,其参数在 RealPayment 中标记为 @Assisted

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);

Check the javadoc of FactoryModuleBuilder class.

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.

Example from the documentation is a RealPayment

public class RealPayment implements Payment {
   @Inject
   public RealPayment(
      CreditService creditService,
      AuthService authService,
      @Assisted Date startDate,
      @Assisted Money 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.

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);
}

And a factory should be binded

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

Configured factory can be injected in your classes.

@Inject
PaymentFactory paymentFactory;

and used in your code

Payment payment = paymentFactory.create(today, price);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文