<?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; guice</title>
	<atom:link href="http://www.factorypattern.com/category/guice/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>Guice Servlets Integration</title>
		<link>http://www.factorypattern.com/guice-servlets/</link>
		<comments>http://www.factorypattern.com/guice-servlets/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 09:36:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[guice]]></category>
		<category><![CDATA[java web apps]]></category>
		<category><![CDATA[servlets]]></category>
		<category><![CDATA[bootstrapping]]></category>
		<category><![CDATA[google guice]]></category>
		<category><![CDATA[web applications]]></category>

		<guid isPermaLink="false">http://www.factorypattern.com/guice-servlets-integration/</guid>
		<description><![CDATA[Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems:
- [...]]]></description>
			<content:encoded><![CDATA[<p>Using Google Guice in web applications can raise some issues. First of all when we talk about web applications we talk about servlets and we talk about managed environments. The creation of servlets in not controlled by us, when we write the application, it is controlled by the web application container. This generates some problems:<br />
- Because we can not control the servlet creation we can not use Guice to inject servlet members in the classic way.<br />
- Bootstrapping: we need a mechanism to bootstrap Guice into the application. The best way is to do it at start up before any http request will be invoked.<br />
<span id="more-37"></span><br />
The key element to bootstrap Google Guice to a java servlet based application is <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html">ServletContext</a>. For each web application there is only one ServletContext instance per JVM. ServletContext is used to manage data which is accessible to all the servlets, and it can be used by the servlets to share data between them. Starting with Servlet 2.3 specification Sun provides a listener mechanism which can be used to instantiate objects at the application start up, outside of any servlet scope in the ServletContext.</p>
<p>This techniques can not be used in distributed environments. If we use it we&#8217;ll have one injector instance on each JVM because on distributed environments for each JVM there is one ServletContext. ServletContext on one JVM is not visible from another JVM, so if we can not use guice scopes distributed on multiple machines.</p>
<h2>Initializing Guice Injector in ServletContext</h2>
<p>As we said there is only one instance of javax.servlet.ServletContext(as long as we don&#8217;t have a distributed application). We can trigger the initialization of the ServletContext using <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html">ServletContextListener</a>. All we have to do is to implement the ServletContextListener.contextInitialized to create the google guice injector, and to set it as an attribute in the ServletContext:</p>
<pre name="code" class="java">package com.exam.web.guice;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

public class GuiceServletContextListener implements ServletContextListener {
    public static final String KEY = Injector.class.getName(); 

    public void contextInitialized(ServletContextEvent servletContextEvent)
    {
    	servletContextEvent.getServletContext()
    		.setAttribute(KEY, getInjector(servletContextEvent.getServletContext()));
    } 

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    	servletContextEvent.getServletContext().removeAttribute(KEY);
    } 

    @SuppressWarnings("unchecked")
    private Injector getInjector(ServletContext servletContext) {
        String className = servletContext.getInitParameter("module");
        try {
            Class<? extends Module> module = (Class<? extends Module>) Class.forName(className);
            return Guice.createInjector(module.getConstructor().newInstance());
        }
        catch (ClassNotFoundException e) { throw new RuntimeException(e); }
        catch (NoSuchMethodException e) { throw new RuntimeException(e); }
        catch (InvocationTargetException e) { throw new RuntimeException(e); }
        catch (IllegalAccessException e) { throw new RuntimeException(e); }
        catch (InstantiationException e) { throw new RuntimeException(e); }
    }
}</pre>
<p>Then we have to change the web.xml to define the listener to be used by the web application container:</p>
<pre name="code" class="xml">
<listener>
<listener-class>
            com.exam.web.guice.GuiceServletContextListener
        </listener-class>
    </listener>
</pre>
<h2>Storing module configuration in web.xml</h2>
<p>We use web.xml to define which module to be used by Guice in <context-param> block. When we create the guice injector the parameter is read and used:</p>
<pre name="code" class="php">String className = servletContext.getInitParameter("module");</pre>
<p>The class name is defined like this in web.xml:</p>
<pre name="code" class="XML">
    <context-param> 
<param-name>module</param-name>
<param-value>com.webapplication.bus.HibernateDaoModule</param-value>
        <description>Guice Module to be used for the servlets app</description>
    </context-param>
</pre>
<p>Finally in the servlet we can use this expression to get the injector:<br />
(Injector) servletContext.getAttribute(GuiceServletContextListener.KEY)</p>
<p>We can add an injector field to the servlet and &#8220;inject&#8221; the injector into it when the servlet is initialized(a super servlet class can be created to define this code in only one place):</p>
<pre name="code" class="java">public class MyServlet  extends HttpServlet {

	Injector injector;
        ...

	@Override
	public void init(ServletConfig config) throws ServletException {

        HibernateUtil.Configure(true);  

	    ServletContext servletContext = config.getServletContext();
	    injector = (Injector) servletContext.getAttribute(GuiceServletContextListener.KEY);
	    injector.injectMembers(this);

	    managersRegistry = injector.getInstance(ManagersRegistry.class);

		super.init(config);
	}
}</pre>
<div style="text-align:center;"><a href="http://api.tweetmeme.com/share?url=http://www.factorypattern.com/guice-servlets/"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http://www.factorypattern.com/guice-servlets/" 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/google-guice-tutorial/" title="Google Guice Tutorial">Google Guice Tutorial</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></ul>]]></content:encoded>
			<wfw:commentRss>http://www.factorypattern.com/guice-servlets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<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>
	</channel>
</rss>

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