97

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?

1

1 Answer 1

203

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);
7
  • 9
    Sought a lot and couldn't find a more concise and clear explanation to my doubts. Many thanks
    – Gabber
    Jun 9, 2014 at 16:54
  • 23
    This is easier to understand than the documentation on Github. Well done.
    – arjabbar
    Mar 23, 2016 at 2:58
  • 9
    Github documentation is crap as compared to this.
    – EMM
    Jul 16, 2016 at 3:36
  • 2
    Shouldn't 'date' and 'amount' be passed along in the method call to 'Payment' ? Why should they be injected here in the constructor ?
    – Harshit
    Jun 5, 2018 at 11:23
  • 5
    For those who wonder, RealPayment does not need to implement an interface. Jul 12, 2019 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.