<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Google Guice</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/google-guice/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Introduction to Google Guice</title>
		<link>http://www.javabeat.net/2007/08/introduction-to-google-guice/</link>
		<comments>http://www.javabeat.net/2007/08/introduction-to-google-guice/#comments</comments>
		<pubDate>Sat, 04 Aug 2007 02:03:46 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Google Guice]]></category>
		<category><![CDATA[Web Frameworks]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=77</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>1) Introduction Google Guice is a Dependency Injection Framework that can be used by Applications where Relation-ship/Dependency between Business Objects have to be maintained manually in the Application code. Since Guice support Java 5.0, it takes the benefit of Generics and Annotations thereby making the code type-safe. This article provides an overview about the Guice [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><h2>1) Introduction</h2>
<p align="justify"><em><strong>Google Guice</strong></em> is a <em><strong>Dependency Injection Framework</strong></em> that can be used by Applications where Relation-ship/Dependency between Business Objects have to be maintained manually in the Application code. Since Guice support Java 5.0, it takes the benefit of <em><strong>Generics</strong></em> and <em><strong>Annotations</strong></em> thereby making the code type-safe. This article provides an overview about the Guice framework with a lot many samples. It then looks into the theories related to <em><strong>Dependency Injection Framework</strong></em> and the advantages of using them in Application. It also explores the various API available in Guice along with the Annotations that simplifies most of the things. The final section presents lots of samples thereby making most of the <em><strong>Guice API</strong></em> to get a much better feel towards the API.</p>
<h2>2) Dependency Injection</h2>
<p align="justify">Since Guice is a <em><strong>Dependency Injection Framework</strong></em>, let us make a clear understanding on <em><strong>Dependency Injection</strong></em> which is gaining more popularity in the recent years and a much needed mechanism to be followed in a typical Application. To name a few, <em><strong>J2EE 5.0</strong></em>, <em><strong>Spring</strong></em>, <em><strong>JBoss Seam</strong></em> are good examples that makes use of Dependency Injection. Now, let us take a simple example to illustrate the need for a Dependency Injection Framework.</p>
<p align="justify">Consider the following scenario. A <code>Storage</code> represents some kind of repository for storing any type of data. If someone asks us to model the (simple) Class Diagram for this kind of situation, then we could have come up with a design very similar to the one mentioned below.</p>
<p><strong>Storage.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">interface Storage{
&nbsp;
    public void store(String uniqueId, Data data);
    public Data retrieve(String uniqueId);
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">The above interface provides a mechanism to store and retrieve <code>Data</code> through its <code>store()</code> and <code>retrieve()</code> methods. Since Data can be stored in a Database or even a File, concrete implementations for the above interface may look something like the following.</p>
<p><strong>FileStorage.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">class FileStorage implements Storage{
&nbsp;
    public void store(String uniqueId, Data data){
        // Store the object in a file using Java Serialization mechanism.
    }
&nbsp;
    public Data retrieve(String uniqueId){
        // Code to retrieve the object.
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">The <code>FileStorage</code> implementation class may store and retrieve Data in a file which is present in a hard disk. Following is another implementation for the <code>Storage</code> interface where every information is stored in a Database.</p>
<p><strong>DatabaseStorage.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">class DatabaseStorage implements Storage{
&nbsp;
    public void store(String uniqueId, Data data){
        // Open a connection and store the data.
    }
&nbsp;
    public Data retrieve(String uniqueId){
        // Get the data from the Database.
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">Now, let us look into a Sample Client Application that makes use of this Client. Following is the Client code snippet which initially makes use of <code>FileStorage</code> implementation and then switches over to <code>DatabaseStorage</code> implementation.</p>
<p><strong>StorageClient.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">public class StorageClient {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        // Making use of file storage. 
        Storage storage = new FileStorage();
        storage.store(&quot;123&quot;, new Data());
&nbsp;
        // Making use of the database.
        storage = new DatabaseStorage();
        storage.store(&quot;456&quot;, new Data());
    }
}</pre></td></tr></table></div>

<p align="justify">Note the code in the Client module carefully. Even though, the interface and the implementation classes enjoys loose coupling, the Client module has to manually create instances to the actual implementation classes. Also the relation-ship between the interface and the implementation classes is maintained directly in the Client code. Since, in most of the cases, during the compilation time itself, the Client Application knows to which implementation classes the corresponding interfaces will bound to, will it be useful if someone takes care of maintaining everything. That&#8217;s what <em><strong>Google Guice</strong></em> does. It takes creating instances in the form of Services from the Application client code and the Dependency between the Clients to its Services is automatically injected through some easy <em><strong>Configuration Mechanism</strong></em>. Following section will provide a simple example that makes use of <em><strong>Guice Framework</strong></em>.</p>
<h2>3) Writing the first simple Guice Example</h2>
<p align="justify">In this very simple example, let us see how <em><strong>Guice</strong></em> simplifies Development life in maintaining the Relation-ship/Dependency between objects. Let us have a look into the following code snippet. Following is the code for the traditional <code>Add</code> interface which defines a method called <code>add()</code> which is to be given implementation by some other class.</p>
<p><strong>Add.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package add.service;
&nbsp;
public interface Add {
&nbsp;
    public int add(int a, int b);
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">This is the class implementing the <code>Add</code> interface which merely returns the sum of two numbers.</p>
<p><strong>SimpleAdd.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package add.service;
&nbsp;
public class SimpleAdd implements Add{
&nbsp;
    public int add(int a, int b) {
        return a + b;
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">This is the <em><strong>Module</strong></em> class which makes use of Guice API to establish <em><strong>Bindings</strong></em> in an Application. Theories towards <em><strong>Module</strong></em> and <em><strong>Bindings</strong></em> are covered in detail in the subsequent sections. For now, just consider that a Module can be configured with some of Bindings which is done through the <em><strong>Binder</strong></em> class. In Guice terms, a <em><strong>Binding</strong></em> refers to the process of providing association to an Interface to its original Implementation.</p>
<p><strong>AddModule.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package add.service;
&nbsp;
import com.google.inject.Binder;
import com.google.inject.Module;
&nbsp;
public class AddModule implements Module{
&nbsp;
    public void configure(Binder binder) {
        binder.bind(Add.class).to(SimpleAdd.class);
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">In the above code, we are telling Guice to bind the implementation for <code>Add</code> interface to <code>SimpleAdd </code>class which literally tells that calls on <code>Add.add()</code> made by the clients will be re-directed to <code>SimpleAdd.add()</code>. Following is the Client code which uses this <code>Add</code> interface.</p>
<p><strong>AddClient.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package add.service;
&nbsp;
import com.google.inject.Guice;
import com.google.inject.Injector;
&nbsp;
public class AddClient {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        Injector injector = Guice.createInjector(new AddModule());
        Add add = injector.getInstance(Add.class);
        System.out.println(add.add(10, 54));
    }
}</pre></td></tr></table></div>

<p align="justify">More theories towards <em><strong>Injector</strong></em>, <em><strong>Guice</strong></em> are yet to come in the subsequent sections. <code>Injector.getInstance(Add.class)</code> will now create and return an instance of type <code>SimpleAdd</code>. Note the concrete implementation class gets bound in the <code>AddModule.configure()</code> method.</p>
<h2>4) Exploring the Guice API</h2>
<p align="justify">Let us explore the various API that makes up the Dependency Injection in Guice. More specifically the following Interfaces/Classes are covered in this section.</p>
<ul>
<li>Binder</li>
<li>Injector</li>
<li>Module</li>
<li>Guice</li>
</ul>
<h3>4.1) Binder</h3>
<p align="justify">This interface mainly consists of information related to <em><strong>Bindings</strong></em>. A Binding refers a mapping for an Interface to its corresponding Implementation. For example, considering the above example, we refer that the interface <code>Add</code> is bound to <code>SimpleAdd</code> implementation.</p>
<p align="justify">Programatically, it is can be mentioned as follows. Note that the class object for both the interface and the implementation classes is passed on to the <code>bind()</code> and the <code>to()</code> methods.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">binder.bind(Add.class).to(SimpleAdd.class)</pre></td></tr></table></div>

<p align="justify">It is also possible to bound an Interface directly to its Instance as the following code suggest that.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">binder.bind(Add.class).to(new SimpleAdd())</pre></td></tr></table></div>

<p align="justify">The third variation is to bind the Interface to its corresponding <code>Provider</code> class. By default, it is the Guice Framework which will instantiate and return objects needed by the Application. But, what if the <em><strong>Object Creation Process</strong></em> needed customization? <em><strong>Providers</strong></em> simply do that. Simply put, Providers follows the traditional <em><strong>Factory Pattern</strong></em> in creating objects. For example, consider the following code snippet,</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">binder.bind(Add.class).to(new AddProvider())</pre></td></tr></table></div>

<p align="justify">We will provide you samples on how to create <em><strong>Provider</strong></em> objects. For the time being, just keep a note that, in some way the <code>AddProvider</code> class provides Factory methods that will return objects of type <code>Add</code>.</p>
<p align="justify">It is also possible to bind an Interface to multiple implementations which will be covered in the later sections.</p>
<h3>4.2) Injector</h3>
<p align="justify"><em><strong>Injectors</strong></em> take care of creating and maintaining Objects that are used by the Clients. Injectors do maintain a set of <em><strong>Default Bindings</strong></em> from where they can take the <em><strong>Configuration information</strong></em> of creating and maintaining Relation-ship between Objects. Consider the following code snippet which will return some implementation of type Add.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">Add addObject = injector.getInstance(Add.class)</pre></td></tr></table></div>

<p align="justify">To get all the <em><strong>Bindings</strong></em> associated with the Injector, simply make a call to <code>Injector.getBindings()</code> method which will return a Map of Binding objects.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">Map&amp;lt;Key, Binding&amp;gt; allBindings = injector.getBindings()</pre></td></tr></table></div>

<p align="justify">Note that every single Binding often has a corresponding <em><strong>Key</strong></em> object which is internally created and maintained by Guice. <em><strong>Providers</strong></em>, if any, which are associated with the <code>Injector</code> can be retrieved by the following method.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">Provider provider = injector.getProvider(SomeType.class)</pre></td></tr></table></div>

<h3>4.3) Module</h3>
<p align="justify"><em><strong>Modules</strong></em> are objects which will maintain the set of <em><strong>Bindings</strong></em>. It is possible to have multiple Modules in an Application. <em><strong>Injectors</strong></em>, in turn, will interact will the Modules to get the possible Bindings. Module is represented by an interface with a method called <code>Module.configure()</code> which should be overridden by the Application to populate the Bindings. To simplify things, there is a class called <code>AbstractModule</code> which directly extends the Module interface. So Applications can depend on <code>AbstractModule</code> rather than <code>Module</code>.</p>
<p align="justify">Consider the following code snippet,</p>
<p><strong>MyModule.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">class MyModule extends AbstractModule{
&nbsp;
    public void configure(Binder binder){
&nbsp;
        // Code that binds information using the various
        // flavours of bind method.
    }
}</pre></td></tr></table></div>

<h3>4.4) Guice</h3>
<p align="justify"><em><strong>Guice</strong></em> is a class which Clients directly depends upon to interact with other Objects. The Relation-ship between <code>Injector</code> and the various modules is established through this class. For example consider the following code snippet,</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">MyModule module = new MyModule();
Injector injector = Guice.createInjector(module);</pre></td></tr></table></div>

<p align="justify">Note that <code>Guice.createInjector()</code> method is passed with a <code>Module</code> Object. Module class must have an overridden method called <code>configure()</code> which is passed with a <em><strong>Default Binder</strong></em> object. This Binder object populates the various Bindings (to Classes, Objects and Providers) that are specific to an Application. Now when a Client requests for an Instance by invoking the <code>getInstance()</code> of the <code>Injector</code> class, Injector in turn will look into the various Bindings maintained by the Binder object to get the original object.</p>
<h2>5) Guice Annotations</h2>
<p align="justify">Guice comes with a small set of useful Annotations that are used to add meta-data values to an Application. Following are the Annotations that are going to get covered in this section.</p>
<ul type="circle">
<li>Implemented By</li>
<li>Inject</li>
<li>Provided By</li>
<li>Singleton</li>
</ul>
<h3>5.1) Implemented By</h3>
<p align="justify">This Annotation points to a Class object that provides Implementation to the interface. For example if the <code>Add </code>interface has multiple implementations and if we wish to have <code>SimpleAdd</code> as the default implementation, then we can say like the following,</p>
<p><strong>Add.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">@ImplementedBy(SimpleAdd.class)
interface Add{
&nbsp;
    public int add(int a, int b);
&nbsp;
}</pre></td></tr></table></div>

<h3>5.2) Inject</h3>
<p align="justify">For injecting instances directly to the Client code, we can use this <em><strong>Inject Annotation</strong></em>. This annotation can be used in a Constructor for a class, for a method or for a Field. For example, consider the following example,</p>
<p><strong>Client.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">class Client{
&nbsp;
    @Inject
    public Client(MyService service){
    }
}</pre></td></tr></table></div>

<p align="justify">The above is an example for <em><strong>Constructor-level Injection</strong></em> assuming that the concrete implementation for the MyService interface would have got bounded by defining them in some Application specific Module. The same applies for <em><strong>Method-level</strong></em> and <em><strong>Field-level Annotations</strong></em>.</p>
<h3>5.3) Provided By</h3>
<p align="justify">Assuming that we want to customize the Object creation process for some interface type, then we would depend on <em><strong>Guice Provider mechanism</strong></em>. Let&#8217;s say, for <code>Add</code> interface we want <code>AddProvider</code> to create and return objects of type <code>SimpleAdd</code>. In such a case, we can qualify what is the <code>Provider</code> type for the Interface by directly annotating it in the Interface declaration. Consider the following code snippet,</p>
<p><strong>Add.java</strong></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">@ProvidedBy(AddProvider.class)
public interface Add{
&nbsp;
}</pre></td></tr></table></div>

<h3>5.4) Singleton</h3>
<p align="justify">By default, when a Client request for Objects by calling <code>Injector.getInstance()</code> multiple times, every new instance is created and returned. If we want to restrict this number by returning one and only instance for the class (which is the <em><strong>Singleton Pattern</strong></em>), the implementation classes can be marked with <em><strong>Singleton Annotation</strong></em>.</p>
<p><strong>MyConnection.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">@Singleton
public class MyConnection{
&nbsp;
    public void connect(){
    }
&nbsp;
    public void disconnect(){
    }
}</pre></td></tr></table></div>

<h2>6) Samples</h2>
<h3>6.1) Introduction</h3>
<p align="justify">This section will provide you plenty of sample Applications that makes use of various <em><strong>Guice API</strong></em>. Let us explore them in much detail.</p>
<h3>6.2) Simple Example</h3>
<p align="justify">This simple example demonstrates the usage of Guice where we don&#8217;t have a separated Interface and Implementation. All we have is a concrete Implementation class and Clients directly depend on them. Though Guice doesn&#8217;t do much here, it is simply provided for reference. Consider the following <code>Player</code> class,</p>
<p><strong>Player.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package simple;
&nbsp;
public class Player {
&nbsp;
public String name;
&nbsp;
    public Player(){		
    }
&nbsp;
    public String toString(){
        return name;
    }
}</pre></td></tr></table></div>

<p align="justify">Following is the example Client that makes use of the Player class. Note that we haven&#8217;t passed anything of type Module to the <code>Guice.createInjector()</code> method simply because we don&#8217;t want anything to be get bound (interface to implementation) in the Application Code.</p>
<p><strong>PlayerTest.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package simple;
&nbsp;
import com.google.inject.Guice;
import com.google.inject.Injector;
&nbsp;
public class PlayerTest {
&nbsp;
public static void main(String[] args) {
&nbsp;
    Injector injector = Guice.createInjector();
    Player player = injector.getInstance(Player.class);
    player.name = &quot;David Boon&quot;;
    System.out.println(player);
    }
}</pre></td></tr></table></div>

<h3>6.3) Resolving Multiple Dependencies</h3>
<p align="justify">In this section, let us see how to resolve multiple Dependencies by making use of <em><strong>@Inject Annotation</strong></em>. Let&#8217;s say that we have an Object which is directly referring two or more Objects. For this simplest case, let the scenario be, &#8216;A person owns a Laptop and a Mobile&#8217;.</p>
<p align="justify">Following is the code for both Mobile and Laptop classes.</p>
<p><strong>Laptop.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package multipledepenedencies;
&nbsp;
public class Laptop {
&nbsp;
    private String model;
    private String price;
&nbsp;
    public Laptop(){
        this.model = &quot;HP 323233232&quot;;
        this.price = &quot;$545034&quot;;
    }
&nbsp;
    public String toString(){
        return &quot;[Laptop: &quot; + model + &quot;,&quot; + price + &quot;]&quot;;
    }
}</pre></td></tr></table></div>

<p><strong>Mobile.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package multipledepenedencies;
&nbsp;
public class Mobile {
&nbsp;
private String number;
&nbsp;
    public Mobile(){
        this.number = &quot;988438434&quot;;
    }
&nbsp;
    public String toString(){
        return &quot;[Mobile: &quot; + number + &quot;]&quot;; 
    }
}</pre></td></tr></table></div>

<p align="justify">Following is the code for the <code>Person</code> class which directly references <code>Laptop</code> and <code>Mobile</code> object. Note the use of <em><strong>@Inject Annotation</strong></em> used on the constructor.</p>
<p><strong>Person.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package multipledepenedencies;
&nbsp;
import com.google.inject.Inject;
&nbsp;
public class Person {
&nbsp;
    private Mobile mobile;
    private Laptop laptop;
&nbsp;
    @Inject
    public Person(Mobile mobile, Laptop laptop){
        this.mobile = mobile;
        this.laptop = laptop;
    }
&nbsp;
    public void diplayInfo(){
        System.out.println(&quot;Mobile:&quot; + mobile);
        System.out.println(&quot;Laptop:&quot; + laptop);
    }
}</pre></td></tr></table></div>

<p align="justify">Following is the Client Code that makes use of this sample. Since we don&#8217;t have anything to do with Bindings, we didn&#8217;t pass any <code>Module</code> object in the <code>Guice.createInjector()</code> method.</p>
<p><strong>MultipleDependencyTest.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package multipledepenedencies;
&nbsp;
import com.google.inject.Guice;
import com.google.inject.Injector;
&nbsp;
public class MultipleDependencyTest {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        Injector injector = Guice.createInjector();
        Person person = injector.getInstance(Person.class);
        person.diplayInfo();
    }
}</pre></td></tr></table></div>

<p align="justify">The above program will output something like the following,</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">Mobile:[Mobile: 988438434]
Laptop:[Laptop: HP 323233232,$545034]</pre></td></tr></table></div>

<h3>6.4) Making use of Binding Annotation</h3>
<p align="justify">In Guice, it is not possible to binding a type to more than one implementations. For example, the following code would result in a Runtime Error.</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">binderObject.bind(SomeType.class).to(ImplemenationOne.class);
binderObject.bind(SomeType.class).to(ImplemenationTwo.class);</pre></td></tr></table></div>

<p align="justify">The following would be consider as an Error in Guice as the SomeType is bounded to more than one implementation classes. This is an Error simply because Guice don&#8217;t know which Instance to be returned upon Client&#8217;s Request. But in language like Java, it is perfectly legal to have multiple implementations for some type T with the concept of interfaces. One way to achieve this way in Guice is to depend on <em><strong>Binding Annotations</strong></em>. For example, consider the <code>Player</code> interface,</p>
<p><strong>Player.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
public interface Player {
&nbsp;
    public void bat();
    public void bowl();
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">Following are the implementations for the <code>Player</code> interface, <code>GoodPlayer</code> and <code>BadPlayer</code>.</p>
<p><strong>GoodPlayer.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
public class GoodPlayer implements Player{
&nbsp;
    public void bat() {
        System.out.println(&quot;I can hit any ball&quot;);
    }
&nbsp;
    public void bowl() {
        System.out.println(&quot;I can also bowl&quot;);
    }
}</pre></td></tr></table></div>

<p><strong>BadPlayer.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
public class BadPlayer implements Player{
&nbsp;
    public void bat() {
        System.out.println(&quot;I think i can face the ball&quot;);
    }
&nbsp;
    public void bowl() {
        System.out.println(&quot;I dont know bowling&quot;);
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">Now we want to instruct to Guice that for the <code>Player</code> interface, we have multiple implementations in the form of <code>GoodPlayer</code> and <code>BadPlayer</code>. Anyway, finally the Client makes use of one of the concrete Implementations only. Either they will use an implementation of type Good Player or Bad Player. Through some <em><strong>Annotation mechanisms</strong></em> we are now going to instruct Guice about the multiple Implementations. Following is the code for that,</p>
<p><strong>PlayerModule.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
import com.google.inject.*;
&nbsp;
public class PlayerModule implements Module{
&nbsp;
    public void configure(Binder binder) {
&nbsp;
        binder.bind(Player.class).annotatedWith(Good.class).to(
            GoodPlayer.class);
        binder.bind(Player.class).annotatedWith(Bad.class).to(
            BadPlayer.class);		
    }
}</pre></td></tr></table></div>

<p align="justify">We have used two custom Annotation types <code>Good</code> and <code>Bad</code>. The above code essentially tells to bind the implementation to <code>GoodPlayer</code> if it is annotated with <code>Good</code> and bind the Player type to <code>BadPlayer</code> if it is annotated with <code>Bad</code>. Following is definition for both the <code>Good</code> and the <code>Bad</code> annotations.</p>
<p><strong>Good.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
import java.lang.annotation.*;
import com.google.inject.BindingAnnotation;
&nbsp;
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
@Target(ElementType. LOCAL_VARIABLE)
public @interface Good {}</pre></td></tr></table></div>

<p><strong>Bad.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
import java.lang.annotation.*;
import com.google.inject.BindingAnnotation;
&nbsp;
@Retention(RetentionPolicy.RUNTIME)
@BindingAnnotation
@Target(ElementType. LOCAL_VARIABLE)
public @interface Bad {}</pre></td></tr></table></div>

<p align="justify">Following is the Client code for the above Program. Note that when requesting for a particular implementation the Client directly specifies the Annotation on the local reference thereby making the Guice to identify the implementation class. The code <code>@Good</code> Player player essentially tells Guice that a concrete implementation of type <code>GoodPlayer</code> has to be injected into the player reference because that is how we have configured in the <code>Player</code> Module.</p>
<p><strong>PlayerClient.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
&nbsp;
public class PlayerClient {
&nbsp;
    public static void main(String[] args) {
&nbsp;
        PlayerModule module = new PlayerModule();
        Injector injector = Guice.createInjector(new Module[]{module});
&nbsp;
        @Good Player player = (Player)injector.getInstance(Player.class);
        player.bat();
        player.bowl();
    }
}</pre></td></tr></table></div>

<h3>6.5) Named Annotations</h3>
<p align="justify">Creating new Annotation types for every concrete implementation doesn&#8217;t provide to be much useful as the sole purpose of having such an Annotation is just to mark the Implementation class instance needed by the Clients. For that we have <em><strong>@Named annotation</strong></em> which can be used to name entities. And there is an utility method called <code>Names.named()</code> which when given a name returns the <code>Named</code> Annotation. For example, in the above Player Module can be replaced with something similar to the following,</p>
<p><strong>PlayerModule.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package playerservice;
&nbsp;
import com.google.inject.Binder;
import com.google.inject.Module;
&nbsp;
public class PlayerModule implements Module{
&nbsp;
    public void configure(Binder binder) {
&nbsp;
        binder.bind(Player.class).annotatedWith(Names.named(&quot;Good&quot;)).to(
            GoodPlayer.class);
        binder.bind(Player.class).annotatedWith(Names.named(&quot;Bad&quot;)).to(
        BadPlayer.class);		
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify"><code>Names.named("SomeName")</code> will simply return an Annotation of type <code>@Named</code> encapsulated with the given name. Now, back in the Client code, we should use the <code>@Named</code> annotation along with the name. For example,</p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">@Named(&quot;Good&quot;) Player goodPlayer = (Player)injector.getInstance(Player.class);
&nbsp;
@Named(&quot;Bad&quot;) Player badPlayer = (Player)injector.getInstance(Player.class);</pre></td></tr></table></div>

<h3>6.6) Writing a Simple Provider</h3>
<p align="justify"><em><strong>Providers</strong></em> are Guice simply acts as <em><strong>Factories</strong></em> in creating and returning Objects. In most of the cases, Clients can directly depend on the Guice Framework for creating Objects for the Services that they are referring. Rarely, the Application code wants to customize the <em><strong>Object creation process</strong></em> for a particular type so as to control the number of objects created, to provide cache mechanism and so on. For that we have to depend on Guice <code>Provider</code> classes.</p>
<p align="justify">For example, let us say that we want to create the Object creation and maintenance process for <code>MockConnection</code> class which is given below.</p>
<p><strong>MockConnection.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package named;
&nbsp;
public class MockConnection {
&nbsp;
    public void connect(){
        System.out.println(&quot;Connecting to the mock database&quot;);
    }
&nbsp;
    public void disConnect(){
        System.out.println(&quot;Dis-connecting from the mock database&quot;);
    }
&nbsp;
}</pre></td></tr></table></div>

<p align="justify">Now let us write a simple <code>Provider</code> class that conforms to Guice Provider that creates and return <code>MockConnection</code> objects. Following is the code for the same.</p>
<p><strong>ConnectionProvider.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package named;
&nbsp;
import com.google.inject.Provider;
&nbsp;
public class ConnectionProvider implements Provider{
&nbsp;
    @Override
    public MockConnection get() {
&nbsp;
        // Do some customization mechanism here.
        MockConnection connection = new MockConnection();
        // Do some customization mechanism here too.
        return connection;
    }	
}</pre></td></tr></table></div>

<p align="justify">Note that all custom <em><strong>Provider</strong></em> class must implement the <code>Provider</code> Interface and should override the <code>get()</code> method to return the objects created in some custom fashion. Now, the module should be aware of the Custom Provider class that so Guice can request the <code>ConnectionProvider</code> to create instances instead of creating them on its own. Following is the Module code along with the Client code.</p>
<p><strong>ConnectionTest.java</strong></p>

<div class="wp_syntax"><table><tr><td class="code"><pre class="language" style="font-family:monospace;">package named;
&nbsp;
import com.google.inject.*;
&nbsp;
public class ConnectionTest {
&nbsp;
    public static void main(String args[]){		
        Injector injector = Guice.createInjector(
            new Module(){
                @Override
                public void configure(Binder binder) {
                    binder.bind(MockConnection.class).toProvider(
                        ConnectionProvider.class);				
                }						
            }				
        );
&nbsp;
        MockConnection connection = 
        injector.getInstance(MockConnection.class);
        connection.connect();
        connection.disConnect();
    }
}</pre></td></tr></table></div>

<p align="justify">Note that in the <code>Module.configure()</code> method, we have bound the type <code>MockConnection.class</code> to a Provider by calling the method <code>Binder.toProvider()</code>.</p>
<h2>6) Conclusion</h2>
<p align="justify">This article started off with the need to<br />
have a <em><strong>Dependency Injection Framework</strong></em> like Guice. Though there are so many Dependency Injection Frameworks coming these days, usage of Guice is simple and the API is also small. There is no need to maintain a separate XML file as all the Configuration related information is nicely encapsulated by means of <em><strong>Module mechanism</strong></em>. In this article the Core API along with the Guice Annotations was explored followed with plenty of Samples.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2F2007%2F08%2Fintroduction-to-google-guice%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/2007/08/introduction-to-google-guice/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/2007/08/introduction-to-google-guice/" data-count="vertical" data-text="Introduction to Google Guice" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/08/introduction-to-google-guice/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
