<?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>My IT-blog &#187; bindings</title>
	<atom:link href="http://dev.eek.be/tag/bindings/feed/" rel="self" type="application/rss+xml" />
	<link>http://dev.eek.be</link>
	<description>IT knowledge exchange</description>
	<lastBuildDate>Fri, 04 Jun 2010 05:34:15 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Dependency Injection with Google Guice by example</title>
		<link>http://dev.eek.be/2009/09/dependency-injection-with-google-guice/</link>
		<comments>http://dev.eek.be/2009/09/dependency-injection-with-google-guice/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 19:22:20 +0000</pubDate>
		<dc:creator>Wim</dc:creator>
				<category><![CDATA[Featured]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[bindings]]></category>
		<category><![CDATA[Dependency injection]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[Google]]></category>
		<category><![CDATA[Guice]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[Inversion of control]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[modules]]></category>
		<category><![CDATA[providers]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://dev.eek.be/?p=66</guid>
		<description><![CDATA[
In this blogpost, I&#8217;ll explain Dependency Injection with Google Guice through a lot of examples. Hope you like it.
Annotation based DI
It&#8217;s possible in Guice to inject a class with the help of annotations. In this example, I create a mainclass which creates an order. Inside the order there will be a payment done. There are [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://dev.eek.be/wp-content/uploads/2009/09/guice2.jpg" alt="guice2" title="guice2" width="300" height="171" class="aligncenter size-full wp-image-149" /><br />
In this blogpost, I&#8217;ll explain <a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank">Dependency Injection</a> with <a href="http://code.google.com/p/google-guice/" target="_blank">Google Guice</a> through a lot of examples. Hope you like it.</p>
<p><u>Annotation based DI</u><br />
It&#8217;s possible in Guice to inject a class with the help of annotations. In this example, I create a mainclass which creates an order. Inside the order there will be a payment done. There are 2 types of payments (by card or cash) and they will be injected by Guice.<br />
<b>Payment</b></p>
<pre class="prettyprint" lang-java>
public interface Payment {
    public void pay();
}
</pre>
<p><b>PaymentCash</b></p>
<pre class="prettyprint" lang-java>
public class PaymentCashImpl implements Payment {
    public void pay() {
        System.out.println("I'll pay just plain cash");
    }
}
</pre>
<p><b>PaymentCard</b></p>
<pre class="prettyprint" lang-java>
public class PaymentCardImpl implements Payment{
    public void pay() {
        System.out.println("I'll pay with a credit card");
    }
}
</pre>
<p><b>Order</b></p>
<pre class="prettyprint" lang-java>
public class Order {

    private Payment payment;

    public Payment getPayment() {
        return payment;
    }

    public void setPayment(Payment payment) {
        this.payment = payment;
    }

    public void finishOrder(){
        this.payment.pay();
    }
}
</pre>
<p><b>Main</b></p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        Order order = new Order();
        Payment payment = new PaymentCardImpl();
        order.setPayment(payment);
        order.finishOrder();
    }
}
</pre>
<p>There isn&#8217;t any Dependency injection in the code above. All the classes are highly coupled into each other. So it&#8217;s time to do some magic:<br />
<b>Payment</b><br />
You can tell through the use of annotations which Payment type is the default implemented class</p>
<pre class="prettyprint" lang-java>
@ImplementedBy(PaymentCardImpl.class)
public interface Payment {
    public void pay();
}
</pre>
<p><b>Order</b><br />
Inject the payment type in the order. What we here say is: Inject the default paymentimplementation, which is set by the @implementedby annotation, into the payment field.</p>
<pre class="prettyprint" lang-java>
public class Order {
    @Inject
    private Payment payment;
....
</pre>
<p><b>Main</b><br />
Lastly, we have to rewrite the main class. In this example, we get an order which uses the PaymentCard as payment type</p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
       Injector injector = Guice.createInjector();
        Order order = injector.getInstance(Order.class);
        order.finishOrder();
    }
}
</pre>
<p>You can run this code. The output should be -I&#8217;ll pay with a credit card-. This code is so cool because if we want to switch to payment with cash at a later point, we just have to change the @implementedBy annotation in the interface and we are done.</p>
<div style="border: 1px solid silver; padding: 8px; background-color: rgb(249, 249, 249); text-align: left;">
<script type="text/javascript"><!--
google_ad_client = "pub-1041875485625119";
/* 160x90, gemaakt 3-6-10 */
google_ad_slot = "3673564135";
google_ad_width = 160;
google_ad_height = 90;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<p><u>Injection types</u><br />
Guice knows different types of injection. The 3 most used are constructor, field and method injection (Examples are based on the above example)<br />
<b>Constructor injection</b></p>
<pre class="prettyprint" lang-java>
import com.google.inject.Inject;

public class Order {
    private Payment payment;

    @Inject
    public Order(Payment payment){
        this.payment=payment;
    }
   ...
}
</pre>
<p><b>Method injection</b></p>
<pre class="prettyprint" lang-java>
import com.google.inject.Inject;

public class Order {
    private Payment payment;

    @Inject
    public void setPayment(Payment payment) {
        this.payment = payment;
    }
   ...
}
</pre>
<p><b>Field injection</b></p>
<pre class="prettyprint" lang-java>
public class Order {
    @Inject
    private Payment payment;
   ...
}
</pre>
<p><u>Module based DI</u><br />
It&#8217;s also possible to use Modules for injecting data. It&#8217;s maybe a little more work but I like it because all the configuration is in the same file. You can compare this with the xml-file in Spring applications.<br />
<b>Payment</b><br />
Remove the @ImplementedBy annotation in the paymentinterface</p>
<pre class="prettyprint" lang-java>
public interface Payment {
    public void pay();
}
</pre>
<p><b>MyModule</b><br />
Next, create the Module class. It has to implement Module, which has one method: configure.<br />
The code speaks for its self. You say nothing more than bind Payment to PaymentCard.</p>
<pre class="prettyprint" lang-java>
public class MyModule implements Module {
    public void configure(Binder arg0) {
        arg0.bind(Payment.class).to(PaymentCardImpl.class);
    }
}
</pre>
<p>Instead of implementing Module, you can also extend AbstractModule. It&#8217;s just a matter of choice.</p>
<pre class="prettyprint" lang-java>
public class MyModule extends AbstractModule {
    public void configure() {
        bind(Payment.class).to(PaymentCardImpl.class);
    }
}
</pre>
<p><b>Main</b><br />
Lastly, we have to put the module into our injector and we are done.</p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        MyModule module = new MyModule();
        Injector injector = Guice.createInjector(module);
        Order order = injector.getInstance(Order.class);
        order.finishOrder();
    }
}
</pre>
<p>The 4 lines in the main class can be written into 1 single line:</p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        Guice.createInjector(new MyModule()).getInstance(Order.class).finishOrder();
    }
}
</pre>
<p><u>Subclassing</u><br />
In Guice, it&#8217;s easy to subclass an implementation.<br />
<b>Payment</b></p>
<pre class="prettyprint" lang-java>
public interface Payment {
    public void pay();
}
</pre>
<p><b>PaymentCardImpl</b></p>
<pre class="prettyprint" lang-java>
public class PaymentCardImpl implements Payment{
    public void pay() {
        System.out.println("I'll pay with a credit card");
    }
}
</pre>
<p><b>PaymentVisaCard</b><br />
extend payment card with paymentvisacard</p>
<pre class="prettyprint" lang-java>
public class PaymentVisaCard extends PaymentCardImpl {
    public void pay() {
        System.out.println("I'll pay with a card from Visa");
    }
}
</pre>
<p>Nothing special in the Main class<br />
<b>Main</b></p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        Guice.createInjector(new MyModule()).getInstance(Payment.class).pay();
    }
}
</pre>
<p><b>MyModule</b><br />
You can specify the hierarchy in the moduleclass</p>
<pre class="prettyprint" lang-java>
public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Payment.class).to(PaymentCardImpl.class);
        bind(PaymentCardImpl.class).to(PaymentVisaCard.class);
    }
}
</pre>
<p>If you run this code, the Visa Card will be used.<br />
<u>Annotationbindings</u><br />
It&#8217;s also possible to use annotations for injection<br />
<b>Payment</b><br />
There&#8217;s nothing special in the interface and implementations:</p>
<pre class="prettyprint" lang-java>
public interface Payment {
    public void pay();
}
</pre>
<p><b>PaymentCardImpl</b></p>
<pre class="prettyprint" lang-java>
public class PaymentCardImpl implements PaymentCashImpl{
    public void pay() {
        System.out.println("I pay with a card");
    }
}
</pre>
<p><b>PaymentCashImpl</b></p>
<pre class="prettyprint" lang-java>
public class PaymentCashImpl implements Payment {
    public void pay() {
        System.out.println("I pay cash");
    }
}
</pre>
<p>Next, we have to created the annotations @cash and @Card<br />
<b>Cash</b></p>
<pre class="prettyprint" lang-java>
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

import com.google.inject.BindingAnnotation;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Cash { }
</pre>
<p><b>Card</b></p>
<pre class="prettyprint" lang-java>
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

import com.google.inject.BindingAnnotation;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Card { }
</pre>
<p><b>Main</b></p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        Guice.createInjector(new PayModule()).getInstance(Order.class).finishOrder();
    }
}
</pre>
<p><b>Module</b><br />
You have to specify which annotations refers to which implementation in the moduleclass</p>
<pre class="prettyprint" lang-java>
public class PayModule extends AbstractModule{
    @Override
    protected void configure() {
        bind(Payment.class).annotatedWith(Cash.class).to(PaymentCashImpl.class);
        bind(Payment.class).annotatedWith(Card.class).to(PaymentCardImpl.class);
    }
}
</pre>
<p><b>Order</b><br />
Now you can use the annotation in your code to inject the right class</p>
<pre class="prettyprint" lang-java>
public class Order {

    @Inject
    private @Card Payment payment;
   ...
</pre>
<p>If you want to chane Cardpayments to Cashpayments, just change the @Card annotation to @Cash</p>
<p><u>Namedannotationbindings</u><br />
You can also use named annotations. This is a Guice annotation where the value is specified inside the moduleclass.<br />
The paymentinterface, the Main and the Cash and Card implementations are the same as the previous example.<br />
<b>Module</b><br />
Give the annotations a name (&#8220;Cash&#8221; and &#8220;Card&#8221;)</p>
<pre class="prettyprint" lang-java>
public class PayModule extends AbstractModule{
    @Override
    protected void configure() {
        bind(Payment.class).annotatedWith(Names.named("Cash")).to(CashPayment.class);
        bind(Payment.class).annotatedWith(Names.named("Card")).to(CardPayment.class);
    }
}
</pre>
<p><b>Main</b></p>
<pre class="prettyprint" lang-java>
 * @author wim
 */
public class Main {
    public static void main(String[] args) {
        Injector inj = Guice.createInjector(new PayModule());
        Order order = inj.getInstance(Order.class);
        order.getPaymentCard().pay();

        Guice.createInjector(new PayModule()).getInstance(Order.class).getPaymentCash().pay();
    }
}
</pre>
<p><b>Order</b><br />
Now you can use them in your order</p>
<pre class="prettyprint" lang-java>
public class Order {

    private Payment paymentCash;
    private Payment paymentCard;

    @Inject
    public void setPaymentCash(@Named("Cash") Payment payment){
        this.paymentCash=payment;
    }

    public Payment getPaymentCash(){
        return paymentCash;
    }

    @Inject
    public void setPaymentCard(@Named("Card") Payment payment){
        this.paymentCard=payment;
    }

    public Payment getPaymentCard(){
        return paymentCard;
    }
}
</pre>
<p>These annotations are very simple but I don&#8217;t recommend them. Guice doesn&#8217;t check them on spelling or validity so they are kinda error prone.<br />
<u>Instancebinding</u><br />
With instancebinding, you can easily give a value to an instance<br />
<b>Module</b><br />
Give a value to a name inside the module</p>
<pre class="prettyprint" lang-java>
public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(String.class)
        .annotatedWith(Names.named("PaymentType"))
        .toInstance("...I'm a Visa Card...");
    }
}
</pre>
<p><b>Main</b></p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        String text = Guice.createInjector(new MyModule()).getInstance(Order.class).getText();
        System.out.println(text);
    }
}
</pre>
<p><b>Order</b><br />
Use the annotation.  The String text will be injected with &#8220;&#8230;I&#8217;m a Visa Card&#8230;&#8221;.</p>
<pre class="prettyprint" lang-java>
public class Order {

    @Named("PaymentType")
    @Inject
    private String text;

    public String getText(){
        return text;
    }
}
</pre>
<p><u>Providers</u><br />
The last example is with the use of providers.<br />
A provider can be used when you have to craete an object. You have to annotate it with the @Provides annotation and the return type is the bound type.<br />
<b>Payment</b></p>
<pre class="prettyprint" lang-java>
public interface Payment {
    void pay();
    int getAmount();
}
</pre>
<p><b>CashPayment</b></p>
<pre class="prettyprint" lang-java>
public class CashPayment implements Payment{

    private int amount;

    public void pay() {
        System.out.println("Inside cashpayment");
    }

    public void setAmount(int amount){
        this.amount=amount;
    }

    public int getAmount(){
        return amount;
    }
}
</pre>
<p><b>Main</b></p>
<pre class="prettyprint" lang-java>
public class Main {
    public static void main(String[] args) {
        Payment payment = Guice.createInjector(new MyModule()).getInstance(Payment.class);
        payment.pay();
        System.out.println(payment.getAmount());
    }
}
</pre>
<p><b>MyModule</b><br />
Inside the module class, we can construct the class and set the amount of payment.</p>
<pre class="prettyprint" lang-java>
public class MyModule extends AbstractModule{

    @Override
    protected void configure() {
    }

    @Provides
    Payment providePayment(){
        CashPayment pay = new CashPayment();
        pay.setAmount(100);
        return pay;
    }
}
</pre>
<p><u>Conclusion</u><br />
You can do more with Guice than described above but that&#8217;s up to you to find out.<br />
<b>I love Guice!!</b> It&#8217;s pretty simple and works very good. You don&#8217;t have to use XML to bind your classes and it&#8217;s very lightweight. If you just wan&#8217;t to use Dependency Injection, Guice is in my opinion the number 1.<br />
<script type="text/javascript">var dzone_url = 'http://dev.eek.be/?p=66';</script><br />
<script type="text/javascript">var dzone_title = 'Dependency Injection with Google Guice by example';</script><br />
<script type="text/javascript">var dzone_blurb = 'Google Guice by example';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/links/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://dev.eek.be/2009/09/dependency-injection-with-google-guice/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
