A java class has a dependency on another class if it uses it as a variable. We want to avoid creating instances of other classes with the new operator because that hard codes the dependency on that class.
Instead we use the @Inject notation, this can inject variables in:
- A constructor - the values of the parameters are injected.
- A method - the values of the parameters are injected. Guice calls the method after the class has been constructed.
- A field - the value of the field is injected after the class is constructed.
Example
Example from IBM DI Tutorial:
@Inject public FrogMan(Vehicle vehicle) { this.vehicle = vehicle; } |
Where Vehicle is an interface.
@Inject public FrogMobile(FuelSource fuelSource){ this.fuelSource = fuelSource; } |
Modules
Example of module from IBM DI Tutorial: |
These modules are used by Guice.createInjector to create the injector.