Created
February 3, 2015 23:56
-
-
Save aasokan/2b6ead78b13fad2d6b44 to your computer and use it in GitHub Desktop.
Guice Assisted Inject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 docummentaiton 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment