This topic is about Google Guice – Overview.
Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google.
Dependency Injection
Every Java-based application has a few objects that work together to present what the end-user sees as a working application. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent.
Consider you have an application which has a text editor component and you want to provide a spell check. Your standard code would look something like this −
public class TextEditor { private SpellChecker spellChecker; public TextEditor() { spellChecker = new SpellChecker(); } }
What we’ve done here is, create a dependency between the TextEditor and the SpellChecker. In an inversion of control scenario, we would instead do something like this −
public class TextEditor { private SpellChecker spellChecker; @Inject public TextEditor(SpellChecker spellChecker) { this.spellChecker = spellChecker; } }
Here, the TextEditor should not worry about SpellChecker implementation. The SpellChecker will be implemented independently and will be provided to the TextEditor at the time of TextEditor instantiation.
Dependency Injection using Guice (Binding)
Dependency Injection is controlled by the Guice Bindings. Guice uses bindings to map object types to their actual implementations. These bindings are defined a module. A module is a collection of bindings as shown below:
public class TextEditorModule extends AbstractModule { @Override protected void configure() { /* * Bind SpellChecker binding to WinWordSpellChecker implementation * whenever spellChecker dependency is used. */ bind(SpellChecker.class).to(WinWordSpellChecker.class); } }
The Module is the core building block for an Injector which is Guice’s object-graph builder. First step is to create an injector and then we can use the injector to get the objects.
public static void main(String[] args) { /* * Guice.createInjector() takes Modules, and returns a new Injector * instance. This method is to be called once during application startup. */ Injector injector = Guice.createInjector(new TextEditorModule()); /* * Build object using injector */ TextEditor textEditor = injector.getInstance(TextEditor.class); }
In above example, TextEditor class object graph is constructed by Guice and this graph contains TextEditor object and its dependency as WinWordSpellChecker object.
In this topic we learned about Google Guice – Overview. To know more, Click Here.