<?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>FactoryPattern.com &#187; Java Frameworks</title>
	<atom:link href="http://www.factorypattern.com/category/java-frameworks/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.factorypattern.com</link>
	<description>Just another Object Oriented Weblog</description>
	<lastBuildDate>Sat, 02 Jan 2010 22:08:06 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Google Guice Tutorial</title>
		<link>http://www.factorypattern.com/google-guice-tutorial/</link>
		<comments>http://www.factorypattern.com/google-guice-tutorial/#comments</comments>
		<pubDate>Thu, 24 Apr 2008 19:49:44 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java Frameworks]]></category>
		<category><![CDATA[Object Oriented Design]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Dependency Inversion]]></category>
		<category><![CDATA[Injector]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/google-guice-tutorial/</guid>
		<description><![CDATA[What is Google Guice
Google Guice is a light java dependency inversion framework using annotations. It is developed by Google(Bob Lee and Kevin Bourrillion) and it is used internally by Google for their applications. Google Guice is sometimes considered an Inversion of Control Container but as their authors state it’s not a container, it’s just an [...]]]></description>
			<content:encoded><![CDATA[<p><H2>What is Google Guice</H2></p>
<p>Google Guice is a light java dependency inversion framework using annotations. It is developed by Google(<a href="http://crazybob.org/">Bob Lee</a> and <a href="http://smallwig.blogspot.com/">Kevin Bourrillion</a>) and it is used internally by Google for their applications. Google Guice is sometimes considered an Inversion of Control Container but as their authors state it’s not a container, it’s just an Dependency Injector, being too<span id="more-20"></span> light to be considered a container. Beside Dependency injection Google Guice does some more AOP stuff. However in this tutorial we are going to talk only about the Dependency Injection part. In order to use Google Guice <a href="http://google-guice.googlecode.com/files/guice-1.0.zip">download</a> it and add the jar from the downloaded zip to the classpath of your application.</p>
<p>First of all let’s take a look on what Google Guice does, then we’ll check how it’s doing it. Let’s take the following sample composed of a few classes:</p>
<p><strong>Customer</strong> – contains the customer data – email address, …<br />
<strong>Notifier</strong> – the interface used to notify a recipient. The customer object contains a reference to the Notifier object.<br />
<strong>SendMail</strong> – an implementation of the Notify interface which notifies a client about the occurred changes by sending an email.<br />
<strong>SendSMS</strong> &#8211; another implementation of the Notify interface notifying a client by sending an SMS.</p>
<p>Let’s see the code when we don’t use any dependency injection framework:</p>
<pre>public class Customer {
      private Notifier notifier;

      public Notifier getNotifier() {
            return notifier;
      }

      public void setNotifier(Notifier notifier) {
            this.notifier = notifier;
      }

      public void changeSomething(){
            this.notifier.sendNotification("This Customer");
      }
}

public interface Notifier {

      public void sendNotification(String to);

}

public class SendMail implements Notifier{

      public void sendNotification(String to){

            System.out.println("Notifying " + to);
      }
}

public class SendSMS implements Notifier{
      public void sendNotification(String to){
            System.out.println("Notifying " + to);
      }
}

public class Main {

      public static void main(String[] args) {

            Customer customer = new Customer();
            Notifier notifier = new SendMail();
            customer.setNotifier(notifier);
            customer.changeSomething();
      }
}</pre>
<h2>Using Google Guice injector with default bindings defined through annotations.</h2>
<p>Now lets use Guice as a dependency injector. First of all we can communicate to Guice the default implementation for the Notifier interface, by using annotations:</p>
<pre>@ImplementedBy(SendMail.class)
public interface Notifier {
    public void sendNotification(String to);
}</pre>
<p>Then we have to change the “application” code. Instead of using new keyword to create a new object we use the getInstance method of the injector Guice creates for us:</p>
<pre>public static void main(String[] args) {
    Injector injector = Guice.createInjector();
    Customer customer = injector.getInstance(Customer.class);
    customer.changeSomething(); // the customer must be notified about the change
}</pre>
<p>Then the last step, we must to tell Guice what to inject in the Customer object. We have here 3 options: Field Injection, Method Injection, Constructor Injection:</p>
<p>1. <strong>Field Injector</strong>  &#8211; Guice will create an object of type Notifier (Guice already knows from the first step that the default implementation for Notifier is SendMail) and inject it in the field “Notifier” of the Customer object. Guice is using reflection here and the interesting part here is that it can inject into private and protected fields as well, breaking the encapsulation:</p>
<pre>@Inject
private Notifier notifier;</pre>
<p>2. <strong>Method Injector</strong>:</p>
<pre>@Inject
public void setNotifier(Notifier notifier) {
    this.notifier = notifier;
}</pre>
<p>3. <strong>Constructor Injector</strong>:</p>
<pre>public class Customer {
…
      @Inject
      public Customer(Notifier notifier) {
            this.notifier = notifier;
      }
…
}</pre>
<p><H2>Defining new bindings</H2></p>
<p>Well done until now, it seems we have everything in place, but what happens if we want to add another notifier class and change the default behavior? Of course we don&#8217;t want to change the annotations in the interfaces changing the default implementation. What we need is to define new bindings. To do this Guice provide a mechanism which assume the creation of another class called Module, that overwrite the bindings. Let&#8217;s say we have another Notifier class, SendSMS and we want to use it. We need to create a module class:</p>
<pre>public class MyModule implements Module{

    public void configure(Binder binder) {
        binder.bind(Notifier.class).to(SendSMS.class);
    }
}</pre>
<p>Now we have the class where we defined the bindings. All we have to do is to tell to the injector to use those bindings. This is how the main method looks:</p>
<pre>public static void main(String[] args) {
    MyModule module = new  MyModule();
    Injector anotherInjector = Guice.createInjector(module);

    Customer customer = anotherInjector.getInstance(Customer.class);
    customer.changeSomething();
}</pre>
<p><H2>Conclusion</H2></p>
<p>We&#8217;ve seen 3 main Google Guice classes in action in this tutorial. Google Guice mainly consists of those classes along with a few other classes which we haven&#8217;t seen in action yet:<br />
<strong>Binder</strong>, <strong>Binding</strong> &#8211; classes responsible for keeping the mapping between interfaces and the implementations that has to be used.<br />
<strong>Injector</strong> &#8211; Fulfills requests for the object instances that make up your application, always ensuring that these instances are properly injected before they are returned.<br />
<strong>Module</strong> &#8211; defines sets of bindings. Modules classes can be used to create injectors (passing a reference to the injector constructor) so the injector uses the binding defined in this.<br />
<strong>Provider</strong> &#8211; provides instances of the applications and can encapsulate some logic to provide one type of implementation or another depending on a context<br />
<strong>Scope</strong> &#8211; helps defining the scope of different injected instances. By scoping Guice offer the option to reuse object instances inside a defined scope (for example reusing objects inside the scope of a session).</p>
<p>In a next part of the tutorial I&#8217;ll try to check in more depth what Google Guice is capable of.</p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/google-guice-tutorial/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/google-guice-tutorial/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/guice-servlets/" title="Guice Servlets Integration">Guice Servlets Integration</a></li><li><a href="http://www.factorypattern.com/multimap-in-google-collections-library/" title="Multimap in Google Collections Library">Multimap in Google Collections Library</a></li><li><a href="http://www.factorypattern.com/google-guice-starts-a-new-google-age/" title="Google Guice Starts a New Google Age?">Google Guice Starts a New Google Age?</a></li><li><a href="http://www.factorypattern.com/how-to-use-ant/" title="How To Use Ant">How To Use Ant</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/google-guice-tutorial/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Multimap in Google Collections Library</title>
		<link>http://www.factorypattern.com/multimap-in-google-collections-library/</link>
		<comments>http://www.factorypattern.com/multimap-in-google-collections-library/#comments</comments>
		<pubDate>Thu, 27 Mar 2008 16:02:04 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Frameworks]]></category>
		<category><![CDATA[Google Collections]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/multimap-in-google-collections-library/</guid>
		<description><![CDATA[<p> I just took the Google Collections Library and start playing with it. I discovered a class I needed in many and many situations in the past. I’m talking about Multimap. Actually Multimap is an interface having a few classes implementing it. Along with some other interfaces it comes to fulfill a gap in the Java Collections. <span id="more-18"></span></p>
<p>Before giving a few examples about it, a few words about Google Collections. This is a really light java framework, build in one jar of about 300 kb. Currently only the Alpha version is released, but it doesn’t mean it’s not tested. In the <a href="http://code.google.com/p/google-collections/wiki/Faq">Google Collection FAQ</a> on <a href="http://code.google.com/">Google Code</a> the authors explain what 0.5 Alpha means” “We already use this library extensively in production for services like GMail, Reader, Blogger, Docs &#038; Spreadsheets, AdWords, AdSense and dozens more. We consider it to be pretty safe. However, during the alpha period, we do reserve the right to make changes of any kind to it at any time.”</p>
<p>All you have to do is to download the latest <a href="http://code.google.com/p/google-collections/">Google Snapshot</a>, unzip google-collect-snapshot-20080321.jar and then add it to your classpath. In our sample we are going to use one class and one interface (classes link to javadocs): <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/HashMultimap.html">com.google.common.collect.HashMultimap</a>, <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html">com.google.common.collect.Multimap</a>. Here is an example of Google Collection in action:</p>
<pre class="prettyprint">Multimap multimap = new HashMultimap();
multimap.put("key1", "value1A");
multimap.put("key2", "value1A");
multimap.put("key1", "value1B");
System.out.println(multimap.get("key1").toString());</pre>
<p>Something similar using Generics:</p>
<pre class="prettyprint">Multimap<String,
Multimap<String,String>> peoples = new HashMultimap<String,Multimap<String,String>>();

Multimap<String,String> vehicles = new HashMultimap<String,String>();
vehicles.put("Ferrari", "Silver Ferrari");
vehicles.put("Ferrari", "Red Ferrari");
vehicles.put("Car", "Honda Civic");
vehicles.put("Bycicle", "33 Gears Bycicle");
peoples.put("Kevin S.", vehicles);

System.out.println(peoples);</pre>
<p>And the final snippet using some classes created by us. We use Google Collection to keep some existing ‘has’ relations:</p>
<pre class="prettyprint">Multimap<Person,
Multimap<String,Vehicle>> samepeoples = new HashMultimap<Person,Multimap<String,Vehicle>>();
Multimap<String,Vehicle> newvehicles = new HashMultimap<String,Vehicle>();
newvehicles.put("Porsche", new Car("Silver Porsche"));
newvehicles.put("Porsche", new Car("Red Porsche"));
newvehicles.put("Car", new Car("Honda Civic"));
newvehicles.put("Bycicle", new Bycicle("33 Gears Bycicle"));
samepeoples.put(new Person("Kevin S."), newvehicles);

System.out.println(samepeoples);</pre>
<p>The result of the test program printed to the console:</p>
<pre>[value1B, value1A]
{Kevin S.=[{Car=[Honda Civic], Ferrari=[Red Ferrari, Silver Ferrari], Bycicle=[33 Gears Bycicle]}]}
{Kevin S.=[{Car=[Honda Civic], Porsche=[Silver Porsche, Red Porsche], Bycicle=[33 Gears Bycicle]}]}</pre>
<p>Here are the classes I created to for the previous snippet:</p>
<pre class="prettyprint">class Person {
	private String name;
	public Person(String name)
	{
		this.name = name;
	}
	public String toString()
	{
		return name;
	}
}
class Vehicle {
	private String name;
	public Vehicle(String name)
	{
		this.name = name;
	}
	public String toString()
	{
		return name;
	}
}
class Car extends Vehicle {
	public Car(String name)
	{
		super(name);
	}
}
class Bycicle extends Vehicle {
	public Bycicle(String name)
	{
		super(name);
	}
}</pre>
<p>Many situations occurred in the past when I had to organize some data in some hierarchical structures. I didn’t want to create some classes keep hierarchical structures so I used hashmaps, hashtables or even sets or lists, storing Set or some other collection as values. Some sort of sets of sets, maps of lists and so on. The Multimap comes to fulfill this need and opens the way for a multitude of uses of collections. Until now, when I thought how I used the collections I felt a little bit that I&#8217;m doing something wrong since is not something that Java Collection was providing. Now, that I know that Google has this class I feel better.</p>
<p>Just think to the coupling degree if we modify the classes to keep association relations. For example a Person class should be enhanced to keep collection of Vehicles so the person class will be coupled with the Vehicle interface. If we just want to  add some 1-to-many relations between some existing classes, changing them might not be the best way of doing it. </p>
Related PostsHow to Read/Write Java Properties FilesGoogle Guice TutorialHow To Use AntHow to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar]]></description>
			<content:encoded><![CDATA[<p> I just took the Google Collections Library and start playing with it. I discovered a class I needed in many and many situations in the past. I’m talking about Multimap. Actually Multimap is an interface having a few classes implementing it. Along with some other interfaces it comes to fulfill a gap in the Java Collections. <span id="more-18"></span></p>
<p>Before giving a few examples about it, a few words about Google Collections. This is a really light java framework, build in one jar of about 300 kb. Currently only the Alpha version is released, but it doesn’t mean it’s not tested. In the <a href="http://code.google.com/p/google-collections/wiki/Faq">Google Collection FAQ</a> on <a href="http://code.google.com/">Google Code</a> the authors explain what 0.5 Alpha means” “We already use this library extensively in production for services like GMail, Reader, Blogger, Docs &#038; Spreadsheets, AdWords, AdSense and dozens more. We consider it to be pretty safe. However, during the alpha period, we do reserve the right to make changes of any kind to it at any time.”</p>
<p>All you have to do is to download the latest <a href="http://code.google.com/p/google-collections/">Google Snapshot</a>, unzip google-collect-snapshot-20080321.jar and then add it to your classpath. In our sample we are going to use one class and one interface (classes link to javadocs): <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/HashMultimap.html">com.google.common.collect.HashMultimap</a>, <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html">com.google.common.collect.Multimap</a>. Here is an example of Google Collection in action:</p>
<pre class="prettyprint">Multimap multimap = new HashMultimap();
multimap.put("key1", "value1A");
multimap.put("key2", "value1A");
multimap.put("key1", "value1B");
System.out.println(multimap.get("key1").toString());</pre>
<p>Something similar using Generics:</p>
<pre class="prettyprint">Multimap<String,
Multimap<String,String>> peoples = new HashMultimap<String,Multimap<String,String>>();

Multimap<String,String> vehicles = new HashMultimap<String,String>();
vehicles.put("Ferrari", "Silver Ferrari");
vehicles.put("Ferrari", "Red Ferrari");
vehicles.put("Car", "Honda Civic");
vehicles.put("Bycicle", "33 Gears Bycicle");
peoples.put("Kevin S.", vehicles);

System.out.println(peoples);</pre>
<p>And the final snippet using some classes created by us. We use Google Collection to keep some existing ‘has’ relations:</p>
<pre class="prettyprint">Multimap<Person,
Multimap<String,Vehicle>> samepeoples = new HashMultimap<Person,Multimap<String,Vehicle>>();
Multimap<String,Vehicle> newvehicles = new HashMultimap<String,Vehicle>();
newvehicles.put("Porsche", new Car("Silver Porsche"));
newvehicles.put("Porsche", new Car("Red Porsche"));
newvehicles.put("Car", new Car("Honda Civic"));
newvehicles.put("Bycicle", new Bycicle("33 Gears Bycicle"));
samepeoples.put(new Person("Kevin S."), newvehicles);

System.out.println(samepeoples);</pre>
<p>The result of the test program printed to the console:</p>
<pre>[value1B, value1A]
{Kevin S.=[{Car=[Honda Civic], Ferrari=[Red Ferrari, Silver Ferrari], Bycicle=[33 Gears Bycicle]}]}
{Kevin S.=[{Car=[Honda Civic], Porsche=[Silver Porsche, Red Porsche], Bycicle=[33 Gears Bycicle]}]}</pre>
<p>Here are the classes I created to for the previous snippet:</p>
<pre class="prettyprint">class Person {
	private String name;
	public Person(String name)
	{
		this.name = name;
	}
	public String toString()
	{
		return name;
	}
}
class Vehicle {
	private String name;
	public Vehicle(String name)
	{
		this.name = name;
	}
	public String toString()
	{
		return name;
	}
}
class Car extends Vehicle {
	public Car(String name)
	{
		super(name);
	}
}
class Bycicle extends Vehicle {
	public Bycicle(String name)
	{
		super(name);
	}
}</pre>
<p>Many situations occurred in the past when I had to organize some data in some hierarchical structures. I didn’t want to create some classes keep hierarchical structures so I used hashmaps, hashtables or even sets or lists, storing Set or some other collection as values. Some sort of sets of sets, maps of lists and so on. The Multimap comes to fulfill this need and opens the way for a multitude of uses of collections. Until now, when I thought how I used the collections I felt a little bit that I&#8217;m doing something wrong since is not something that Java Collection was providing. Now, that I know that Google has this class I feel better.</p>
<p>Just think to the coupling degree if we modify the classes to keep association relations. For example a Person class should be enhanced to keep collection of Vehicles so the person class will be coupled with the Vehicle interface. If we just want to  add some 1-to-many relations between some existing classes, changing them might not be the best way of doing it. </p>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/multimap-in-google-collections-library/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/multimap-in-google-collections-library/" height="61" width="51" /></a></div><h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li><a href="http://www.factorypattern.com/how-to-readwrite-java-properties-files/" title="How to Read/Write Java Properties Files">How to Read/Write Java Properties Files</a></li><li><a href="http://www.factorypattern.com/google-guice-tutorial/" title="Google Guice Tutorial">Google Guice Tutorial</a></li><li><a href="http://www.factorypattern.com/how-to-use-ant/" title="How To Use Ant">How To Use Ant</a></li><li><a href="http://www.factorypattern.com/how-to-write-ant-xml-build-file-generate-jaxb-code-compile-build-jar/" title="How to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar">How to write an Ant xml build file to Generate JAXB Code and Compile and Build it to a Jar</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/multimap-in-google-collections-library/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.712 seconds -->
