Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
227 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...