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?
-
related, the answers below are not covering cases where he same type is used multiple times. https://stackoverflow.com/questions/23553865/using-assisted-inject-with-multiple-params-of-same-type-named-params – Alexander Oh Nov 13 '17 at 14:42
1 Answers
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);

- 9,691
- 1
- 31
- 48

- 7,939
- 3
- 35
- 51
-
8Sought a lot and couldn't find a more concise and clear explanation to my doubts. Many thanks – Gabber Jun 09 '14 at 16:54
-
22This is easier to understand than the documentation on Github. Well done. – arjabbar Mar 23 '16 at 02:58
-
9
-
2Shouldn't 'date' and 'amount' be passed along in the method call to 'Payment' ? Why should they be injected here in the constructor ? – Harshit Jun 05 '18 at 11:23
-
5For those who wonder, `RealPayment` does not need to implement an interface. – jsallaberry Jul 12 '19 at 17:51
-
Filed a github issue to improve their docs using this answer - https://github.com/google/guice/issues/1287 – coding_idiot Jan 15 '20 at 01:06
-
just curious, what happens if we add @Singleton annotation on RealPayment class? – stallion May 14 '20 at 19:28