How to use Guice's AssistedInject?

落爺英雄遲暮 提交于 2019-11-29 19:41:54
Mairbek Khadikov

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!