In summary though, dependency injection allows you to configure how and where your objects receive their external dependencies. It also eliminates all of the overhead/boiler-plate code associated with obtaining those dependencies. Another benefit is that the configurations for dependencies can be swapped out at run time to avoid recompiling or recoding a project.
With dependency injection, you just say "these are the external dependencies my object needs to function." Guice will do dependency analysis on those dependencies, and their dependencies, and so on until they can all be resolved and provided.
Here is a quick example of Guice in action:
You might have a car class called Car.java:
import car.Exterior;
import car.Interior;
import car.Engine;
import car.Chassis;
class Car {
private final Exterior exterior;
private final Interior interior;
private final Engine engine;
private Chassis chassis;
@Inject
public Car(Engine engine, Exterior exterior, Interior interior, Chassis chassis) {
this.engine = engine;
this.exterior = exterior;
this.interior = interior;
this.chassis = chassis;
}
}
Notice the @Inject annotation. That is a Guice annotation which signifies that our constructor is an injection point for dependencies. This means Guice will analyze all the parameters types and provide each parameters based on how it was configured.
To configure Guice, you setup modules which contain various ways of providing dependencies. The easiest and most common is a binding. A binding maps a class type to an implementation. So you might have a PorscheModule that looks like this in PorscheModule.java:
import car.*;
class PorscheModule extends AbstractModule {
protected void configure() {
bind(Engine.class).to(PorscheEngine.class);
bind(Exterior.class).to(PorscheExterior.class);
bind(Interior.class).to(PorscheInterior.class);
bind(Chassis.class).to(PorscheChassis.class);
}
}
So above we have setup a module which configures how each of the dependencies for Car should be provided. Next we put it all together in Main.java:
class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new PorscheModule());
Car myCar = injector.getInstance(Car.class);
}
}
In this case, you would get a porsche from Guice because that's what module was loaded into it. Sweet!
So you can basically think of Guice as a fancy, dynamic, configurable factory that does all the work of dependency analysis and creation for you.
Here's the Guice creators talking all about how Guice will change your life:

New Topic/Question
Reply



MultiQuote







|