<?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>Sonatype Blog &#187; developer</title>
	<atom:link href="http://blog.sonatype.com/people/tag/developer/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sonatype.com/people</link>
	<description>Sonatype is transforming software development with tools, information and services that enable organizations to build better software, faster, using open-source components.</description>
	<lastBuildDate>Thu, 16 May 2013 18:53:09 +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>What&#039;s in Maven 3.0 for Plugin Authors?</title>
		<link>http://blog.sonatype.com/people/2010/11/whats-in-maven-3-0-for-plugin-authors/</link>
		<comments>http://blog.sonatype.com/people/2010/11/whats-in-maven-3-0-for-plugin-authors/#comments</comments>
		<pubDate>Wed, 17 Nov 2010 17:14:11 +0000</pubDate>
		<dc:creator>Bentmann Benjamin</dc:creator>
				<category><![CDATA[Maven]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://www.sonatype.com/people/?p=6490</guid>
		<description><![CDATA[While Maven 3 is a dramatic improvement over Maven 2 from the perspective of performance, extensibility, and architecture, most end-users are motivated by plugins. This has been true about Maven from the beginning, while the framework has value, it is the plugins that make the difference. This blog focuses on the changes that are of [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.sonatype.com/people/wp-content/uploads/2009/10/maven.png"><img src="http://www.sonatype.com/people/wp-content/uploads/2009/10/maven.png" alt="" title="maven" width="250" height="72" class="alignright size-full wp-image-3145" /></a></p>

<p>While Maven 3 is a dramatic improvement over Maven 2 from the perspective of performance, extensibility, and architecture, most end-users are motivated by plugins.   This has been true about Maven from the beginning, while the framework has value, it is the plugins that make the difference.  This blog focuses on the changes that are of interest to plugin authors.</p>

<p><span id="more-6490"></span></p>

<h2>Accessing Project Dependencies</h2>

<p>The easiest way for a plugin to get the entire set of transitive dependencies for a project is the mojo annotation @requiresDependencyResolution. This annotation is configured with one of the values: compile, runtime or test, which denote the dependency scope a plugin is interested in. What has been proven troublesome is the subtle fact that the runtime classpath is not a superset of the compile classpath, i.e. dependencies of scope provided and system are not included in the runtime classpath.</p>

<p>Now, what shall plugin authors do that need to inspect the union of the compile and runtime classpaths? So far, the answer was either to request the test classpath or to programmatically do dependency resolution with the proper scope filter. Neither of these two approaches are really attractive for one reason or the other. So we eventually added support for a new annotation value in Maven 3.0, compile+runtime, that ensures project dependencies with the scopes compile, runtime, provided and system get resolved.</p>

<h2>Requiring Dependency Collection</h2>

<p>While we are at dependency resolution, Maven 3.0 also introduces the new annotation @requiresDependencyCollection. Admittedly, the name of this new annotation differs only slightly from the existing @requiresDependencyResolution annotation but there&#8217;s a rather important difference regarding the effect.</p>

<p>Dependency resolution consists of two phases. Phase one is determining the coordinates of all the transitive dependencies, phase two is getting the files for these artifacts which potentially involves downloading them. If one is only interested in phase one, we talk about dependency collection. In more detail, if a plugin goal declares @requiresDependencyCollection compile, it can inspect all transitive compile time dependencies of the project via MavenProject.getArtifacts(). But unlike @requiresDependencyResolution, the returned artifact instances might be unresolved, i.e. have no file associated with them.</p>

<p>It might seem odd to have unresolved artifacts but let me try to sketch the use cases that motivate this. While unresolved artifacts can not be used to create classpaths, they still allow a plugin to inspect the set of transitive dependencies, look for unwanted artifacts, check versions etc. If that reminds you of the Maven Release Plugin or the Maven Enforcer Plugin, great. Those plugins and others are usually invoked in very early lifecycle phases of the build, in particular, before any artifacts have been packaged or even any classes have been compiled. If those plugins try to resolve dependencies during a multi-module build with inter-project dependencies, they can&#8217;t succeed, what hasn&#8217;t been built yet cannot be resolved.</p>

<p>In Maven 2.x, there&#8217;s a hack that tolerates resolution errors if all of the missing artifacts are in the reactor but it still leaves your build with an ugly warning and the plugin in question with unsatisfied requirements. @requiresDependencyCollection is the answer to this situation and will help to eventually fix some long-standing issues in the previously-mentioned plugins. So if your plugin doesn&#8217;t need the actual files but only the coordinates of the project dependencies, consider to use the new annotation when targetting Maven 3.0 as a prerequisite.</p>

<h2>Writing Thread-safe Maven Plugins</h2>

<p>Related to the new support for <a href="https://cwiki.apache.org/confluence/display/MAVEN/Parallel+builds+in+Maven+3">parallel building in Maven 3.0</a>, there&#8217;s also a new mojo annotation @threadSafe. Right now, this annotation is nothing more than an informative suggestion. When Maven 3.0 is asked to perform a parallel build and encounters a plugin that isn&#8217;t marked as thread-safe, it will print a <b>prominent warning</b> that your build might fail as historically, plugin authors assumed a sequential execution and, as such, didn&#8217;t code with concurrency and thread safety in mind.</p>

<p>Unlike the previously mentioned extension to the Mojo API, this new annotation can be safely added to a plugin that targets Maven 2.x as runtime. So once you have reviewed your code and possibly adjusted it to support concurrent mojo execution, feel free to add this annotation to disable the build warning from Maven 3.0.  In addition to disabling the warning, the generated plugin site will also indicate that the goal supports parallel builds.</p>

<h2>Using Generics with Maven Plugins</h2>

<p>Given that Maven 2.2.x already requires Java 1.5 to run, more and more plugins are moving to Java 1.5 as well. To enable the benefits of Java 1.5, the Maven API has been updated to use generics, thereby easing plugin coding. Furthermore, Maven 3.0 allows to use enums for plugin configuration parameters.</p>

<h2>Fixes to the Classloader Hierarchy</h2>

<p>The last change I want to mention is the reworked class loader hierarchy. Build extensions can now contribute additional APIs and components that other plugins can utilize during the build. The APIs and components contributed by extensions are shared across all projects using the same extension which allows plugins to easily exchange domain-specific data structures during the build, e.g. via MavenProject.getContextValue() or via some stateful singleton from the extension. If that sounds interesting to you, have a look at the wiki article <a href="https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Class+Loading">Maven 3.x Class Loading</a> which describes the revised class loading in more depth.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sonatype.com/people/2010/11/whats-in-maven-3-0-for-plugin-authors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Documenting the Nexus REST API with Enunciate</title>
		<link>http://blog.sonatype.com/people/2010/02/documenting-the-nexus-rest-api-with-enunciate/</link>
		<comments>http://blog.sonatype.com/people/2010/02/documenting-the-nexus-rest-api-with-enunciate/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 17:31:15 +0000</pubDate>
		<dc:creator>Tamas Cservenak</dc:creator>
				<category><![CDATA[Nexus]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[documentation]]></category>
		<category><![CDATA[enunciate]]></category>
		<category><![CDATA[nexus pro]]></category>
		<category><![CDATA[rest]]></category>

		<guid isPermaLink="false">http://www.sonatype.com/people/?p=4301</guid>
		<description><![CDATA[Nexus OSS Core has more than 120 REST Resources published. And that number is just increasing with new Nexus Plugins. Not to mention Nexus Pro that comes with even more plugins and more REST resources.    Everything you do in Nexus, whether you use the Maven Nexus plugin or the Nexus UI, is interacting with [...]]]></description>
				<content:encoded><![CDATA[<p><strong><a href="http://www.sonatype.com/people/wp-content/uploads/2010/01/nexus-small.png"><img class="alignright size-full wp-image-3683" title="nexus-small" src="http://www.sonatype.com/people/wp-content/uploads/2010/01/nexus-small.png" alt="" width="250" height="62" /></a>Nexus OSS Core has more than 120 REST Resources</strong> published. And that number is just increasing with new Nexus Plugins. Not to mention Nexus Pro that comes with even more plugins and more REST resources.    Everything you do in Nexus, whether you use the Maven Nexus plugin or the Nexus UI, is interacting with a REST service that is available to you if you want to write your own customizations and scripts.   It has been this way since we started the project in 2007.  In this post, I&#8217;m going to discuss how this came to be, how Nexus was developed with REST in mind from the beginning.</p>

<h3>Nexus: A Core of REST Services</h3>

<p>When we started the Nexus project, I called it a &#8220;blind&#8221; application.  A &#8220;blind&#8221; webapp is one with no UI technology whatsoever built-in.   All it publishes is a few static files, and a REST API.   All of the UI that you see in Nexus is Javascript.   Your browser executes Javascript which, in turn, interacts with a set of services.   The only presentation technology on the server side is a trivial Velocity template used to render the initial &#8220;shell&#8221; of the page.<span id="more-4301"></span></p>

<p>The server-side application you call Nexus, doesn&#8217;t generate the UI, that is all Javascript.   It is a completely separate and standalone application, that runs in your browser! A self contained JavaScript application (powered by ExtJS), that communicates with Nexus server, using REST calls only.  This has one very important consequence: whatever Nexus functionality you are able to reach using the Nexus User Interface (and I do mean <em>all</em>), you can do with a plain REST client.     If you want to automate a task, you can use a tool like <tt>curl</tt>, or some Ruby script, or any HTTP capable client.   You can even start to implement your own custom interface if you would like a completely customized UI.</p>

<p>As I said, it was like this since day one. But, we always had one major issue that prevented wider acceptance of Nexus&#8217; REST API: <strong>we had no up-to-date documentation for it</strong>.    It wasn&#8217;t a priority, we spent much of our time trying to integrate the only existing REST framework (restlet.org) with Plexus, and since we were moving so quickly to implement new features, we didn&#8217;t think it made sense to stop and document an ever-changing interface.  We did maintain a <a rel="nofollow" href="https://docs.sonatype.com/display/NX/Nexus+Rest+API">wiki page</a> which described the REST services from the beginning of the project, it always provided stale information given our aggressive development pace.</p>

<h3>REST Documentation: Using Enunciate</h3>

<p>I&#8217;ve been looking at the <a rel="nofollow" href="http://enunciate.codehaus.org/">Enunciate</a> project for some time, and it appears to be the solution to our REST document issues.  Enunciate is a cool project hosted on <a href="http://codehaus.org"><span style="color: #003366;">Codehaus</span></a>, with a bold promise:</p>

<p><em>Enunciate is designed to make your life easier. Enunciate deals with your deployment difficulties, documentation, and client-side code. By using Enunciate to publish your service interfaces, not only will you have all three Web service interfaces (SOAP, REST, and AMF), but you&#8217;ll also have full up-to-date documentation generated, strongly typed ActionScript code that you can use to invoke your remote services from your Flex code, and rich client-side libraries that can be used to access your Web services from a variety of platforms (including Mac/iPhone).</em></p>

<p>Our initial plans are to use Enunciate in a &#8220;lite&#8221; mode to <strong>generate documentation</strong> (and potentially client side code) for our current REST API. Later, we plan to integrate it more closely into new Nexus &#8220;Remoting API&#8221; implementation, and it will be the backbone of our REST services when we will implement version 2.0 of our API.</p>

<p>Here is just a taste of what is to come.  We&#8217;ve used Enunciate to generate documentation for our REST services, and the work is proceeding very quickly.   Here is a snapshot of the documentation we will be releasing soon.</p>

<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim1.png"><img class="aligncenter size-medium wp-image-4303" title="Nexus Enunciate Sample #1" src="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim1-300x256.png" alt="" width="300" height="256" /></a></p>

<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim2.png"><img class="aligncenter size-medium wp-image-4304" title="Nexus Enunciate Sample #2" src="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim2-300x230.png" alt="" width="300" height="230" /></a></p>

<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim3.png"><img class="aligncenter size-medium wp-image-4316" title="Enunciated Nexus REST API Sample #3" src="http://www.sonatype.com/people/wp-content/uploads/2010/02/tim3-300x263.png" alt="" width="300" height="263" /></a></p>

<h3>Remaining Problems to Solve</h3>

<p>When our REST API was concieved in Q4 of 2007 we didn&#8217;t have the rich array of options that we have today.   One major REST library was available, and that was <a rel="nofollow" href="http://www.restlet.org/">Restlet</a>.  JSR311 wasn&#8217;t around back then, so we were forced to code directly to the Restlet API.  Back in 2007, it was very cool to create Plexus components that were then automatically published as REST Resources in Nexus. But today, the same thing looks very cumbersome and is not what one would call a &#8220;state of the art&#8221;. Back then, we had these goals in mind:</p>

<ul>
    <li>have complete REST API published on Nexus</li>
    <li>have a decoupled UI application</li>
    <li>provide XML/JSON serialized transport to REST Resource without any effort, with proper content negotiation (XML was kept as &#8220;Plan B&#8221;)</li>
    <li>make our REST Resources as Plexus components (to enjoy all the benefits of IoC, and later pluggability)</li>
</ul>

<p>While we fulfilled much of these goals above, we did that at a high cost.  For a Nexus core developer (or Nexus plugin developer), it is very cumbersome to create a new REST Resource using our classes, compared to what REST libraries are available today. Current state-of-the-art REST libraries make our initial implementation seem somewhat naive (hence the need to move toward new libraries like Enunciate). Our 1st and biggest mistake was a very deep class hierarchy in our current API.  While all the &#8220;defaults&#8221; are properly configured, it is often difficult to create a non-trivial Resource in the current API if you are not intimately familiar with the system.</p>

<p>Also, in the initial design, we use XStream with a custom driver to produce JSON. Back then, it was a real pain to produce proper JSON out of Java.   Today, we have libraries like Jackson.   In the next interation of refactoring, you&#8217;ll see update the infrastructure used to produce our REST services to bring it up to speed with what is available today.</p>

<h3>The Benefits of &#8220;enunciating&#8221; a REST API</h3>

<p>At first, we will use Enunciate with Nexus during build time only, to generate HTML documentation of our REST API. This documentation will be available publicly, but will also be bundled with every Nexus instance!   Our work to modify our own REST infrastructure is going to require some &#8220;invasive&#8221; work, but I have to emphasize that Enunciate is not invasive if you use it on a modern JSR311 based REST applications. Enunciate is invasive for us only, since we are about to use it on a home grown, non-JSR311 REST application.</p>

<p>Enunciate gathers and builds your services model using your sources and all the metadata it finds (Java5 annotations, Javadoc).  To &#8220;enunciate&#8221; the Nexus REST API, we had to add JSR311 annotations to our existing REST Resources.  There was one more problem to solve: our method signatures are more &#8220;servlet like&#8221;, and they didn&#8217;t fit the model of a JSR311 REST Application. While a JSR311 application method signature completely describes the method expectations about payload, parameters, and response type, our methods – whether GET, PUT, POST or DELETE – have almost same signature: RestRequest, RestResponse, Variant. Hence, we had to add more metainformation describing what a method does: what it expects as input, if any, and what it sends out as response.</p>

<p>Luckily, it turned out that this was the only piece missing, and Enunciate was happy to generate documentation for us. Ryan added the new annotation that describes the &#8220;alternate REST Signature&#8221; of the method, and Enunciate got all the information it needed to generate documentation for us.</p>

<p>Another painful step yet to be completed is &#8220;freeing&#8221; our REST DTOs from Modello. Initially, we knew we wanted to <em>version</em> the DTOs used in REST. Hence, we used Modello to generate the DTOs. Later, problems with Modello and Restlet forced us to always use version 1.0 of our REST DTOs. Since Enunciate requires that DTOs have JAXB2 annotations, we decided to store our DTOs as code and ditch Modello in our builds.</p>

<p>All this looks like a lot of work, but it is actually pretty straightforward.   While this might seem dull to someone not developing Nexus, this work is going to bring real value once it is completed.    In addition to solving our documentation problems, Enunciate is going to open up a world of possibilities once we migrate our REST services over to the framework.</p>

<p>For more information about Enunciate, the <a rel="nofollow" href="http://docs.codehaus.org/display/ENUNCIATE/Enunciate">Enunciate Wiki</a> contains a nice example of how to use Enunciate in case like ours is, without JAX-RS. Example is shown <a rel="nofollow" href="http://docs.codehaus.org/display/ENUNCIATE/Leveraging+Enunciate+Without+JAX-*S">here</a>.  Examples of Enunciate generated documentation can be seen on it&#8217;s <a rel="nofollow" href="http://enunciate.codehaus.org/">site</a>. There is a great walk-through, with <a rel="nofollow" href="http://enunciate.codehaus.org/wannabecool/step4/index.html">static examples</a>.</p>

<h3>Expect More Changes in the Next Few Months</h3>

<p>As Nexus graduated from alphas, betas and now is at a 1.5.0 version, we realize we have to change gears to keep up. Enunciate is the 1st &#8220;newcomer&#8221; technology to Nexus stack.  There will be more to come.   Think of this as the Nexus 100,000 mile checkup.  We&#8217;re taking a look at the stack and taking this as an opportunity to upgrade where necessary.</p>

<p>One last note, this post is not about any deficiencies in Restlet.  Restlet is a great framework, and it served us well.  We – the Nexus Project team – are <strong>very thankful</strong> to Restlet.org project with all the help we got from them and for the great library they made.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sonatype.com/people/2010/02/documenting-the-nexus-rest-api-with-enunciate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Plexus to Guice (#3): Creating a Guice Bean Extension Layer</title>
		<link>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-3-creating-a-guice-bean-extension-layer/</link>
		<comments>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-3-creating-a-guice-bean-extension-layer/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 09:00:53 +0000</pubDate>
		<dc:creator>Stuart McCulloch</dc:creator>
				<category><![CDATA[Maven]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[plexus]]></category>

		<guid isPermaLink="false">http://www.sonatype.com/people/?p=3981</guid>
		<description><![CDATA[In the first two articles in this series you learned why Sonatype has decided to move our development efforts from Plexus to Guice and you&#8217;ve also been introduced to Sonatype&#8217;s efforts to create a Guice/Plexus integration library to make the migration from Plexus to Guice seamless.   In this post, I&#8217;m going to dive into [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/01/from-plexus-to-guice1.png"><img class="alignright size-full wp-image-4024" title="from-plexus-to-guice" src="http://www.sonatype.com/people/wp-content/uploads/2010/01/from-plexus-to-guice1.png" alt="" width="250" height="62" /></a>In the first two articles in this series you learned why<a href="http://www.sonatype.com/people/2010/01/from-plexus-to-guice-1-why-guice/"> Sonatype has decided to move our development efforts from Plexus to Guice</a> and you&#8217;ve also been introduced to Sonatype&#8217;s efforts to create a <a href="http://www.sonatype.com/people/2010/01/from-plexus-to-guice-2-the-guiceplexus-bridge-and-custom-bean-injection/">Guice/Plexus integration library</a> to make the migration from Plexus to Guice seamless.   In this post, I&#8217;m going to dive into the details of bean injection in Guice, and I&#8217;m going to demonstrate how you can use the general-purpose bean injection layer in the Guice/Plexus integation library to intialize a bean.  This post is highly technical and is meant for developers interested in the details of our attempts to bridge Plexus and Guice.<span id="more-3981"></span></p>

<p><strong>Guice-Bean Extension Layer</strong></p>

<p>Our goal is to create a general-purpose bean injection layer on top of the raw <a title="2. Customizing Guice Injection" href="https://docs.sonatype.com/display/OSGI/2.+Customizing+Guice+Injection">custom injection</a> API provided by Guice. This layer will take care of registering the necessary <tt>MembersInjectors</tt> as well as scanning class hierarchies for potential bean properties. All the client needs to do is decide whether or not to supply a binding for a given property.  The primary class in this layer is <tt>BeanListener</tt>:</p>

<div>
<div><strong>org.sonatype.guice.bean.inject.BeanListener</strong></div>
<div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> BeanListener
    <span style="color: #000000; font-weight: bold;">implements</span> TypeListener
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> BeanListener<span style="color: #009900;">&#40;</span> <span style="color: #000000; font-weight: bold;">final</span> BeanBinder beanBinder <span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// ...etc...</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>



</div>
</div>

<p>This is a <tt>TypeListener</tt> implementation that you can register with Guice to provide bean injection for any type. It accepts a single argument of type <tt>BeanBinder</tt>, which the client is expected to implement:</p>

<div>
<div><strong>org.sonatype.guice.bean.inject.BeanBinder</strong></div>
<div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> BeanBinder
<span style="color: #009900;">&#123;</span>
    <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>B<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> PropertyBinder bindBean<span style="color: #009900;">&#40;</span> TypeLiteral<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>B<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> type, TypeEncounter<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>B<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> encounter <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>



</div>
</div>

<p>The single <tt>bindBean</tt> method should supply a <tt>PropertyBinder</tt> based on the type of bean being injected. This means clients can customize or cache information on a per-type basis, or simply provide the same <tt>PropertyBinder</tt> implementation for all bean types. Returning <tt>null</tt> will disable bean injection for that type.  The <tt>PropertyBinder</tt> interface does the same job as <tt>BeanBinder</tt>, but at the property level:</p>

<div>
<div><strong>org.sonatype.guice.bean.inject.PropertyBinder</strong></div>
<div>
<pre>public interface PropertyBinder
{
    &lt;T&gt; PropertyBinding bindProperty( BeanProperty&lt;T&gt; property );
}</pre>
</div>
</div>

<p>This is the point where clients decide whether or not to bind a particular property. They can either return an implementation of <tt>PropertyBinding</tt> which should inject the property, or return <tt>null</tt> to ignore this property. This process continues until all the bean properties have been scanned &#8211; unless the client returns the <tt>LAST_BINDING</tt> constant from the <tt>PropertyBinder</tt> API, which will immediately stop the scanning for the current bean. <tt>LAST_BINDING</tt> is supposed to be used by binders who know they can&#8217;t supply any more bindings, because then there&#8217;s no point in continuing the scan.  So what does a <tt>PropertyBinding</tt> look like?</p>

<div>
<div><strong>org.sonatype.guice.bean.inject.PropertyBinding</strong></div>
<div>
<pre>public interface PropertyBinding
{
    &lt;B&gt; void injectProperty( B bean );
}</pre>
</div>
</div>

<p>Well, not much as you can see! It has a single method <tt>injectProperty</tt> which is the trigger for injecting a value into the appropriate property of the given bean. How this value is created and how it is injected into the bean is up to the client, but most clients will use the <tt>BeanProperty</tt> supplied in the original <tt>bindProperty</tt> method to do the actual injection:</p>

<div>
<div><strong>org.sonatype.guice.bean.reflect.BeanProperty</strong></div>
<div>
<pre>public interface BeanProperty&lt;T&gt;
{
    &lt;A extends Annotation&gt; A getAnnotation( Class&lt;A&gt; annotationType );

    TypeLiteral&lt;T&gt; getType();

    String getName();

    &lt;B&gt; void set( B bean, T value );
}</pre>
</div>
</div>

<p>Specifically the <tt>set</tt> method lets you inject a value into this property for a given bean instance. Notice how you can also query the generic type, name, as well as any annotations attached to the bean property. You can use any or all of this information to determine what value to inject into the property: for example by querying XML metadata, runtime annotations, maybe even pulling values out of a database.</p>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>Property names are normalized &#8211; a setter method called &#8220;setValue&#8221; has a property name of &#8220;value&#8221;</td>
</tr>
</tbody>
</table>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>The <tt>BeanProperty</tt> currently doesn&#8217;t tell you whether it&#8217;s backed by a field or setter method. This is because we don&#8217;t need this information in our use-case and don&#8217;t believe others will, but some sort of query method could be added in the future if necessary.</td>
</tr>
</tbody>
</table>
</div>

<p>Enough talk, let&#8217;s actually try and use this extension layer in a small example!</p>

<h3>Example</h3>

<p>We begin by creating an example Maven project:</p>

<div>
<div>
<pre>mvn archetype:create "-DgroupId=example.bean.guice" "-DartifactId=guice-bean-example"

cd guice-bean-example/</pre>
</div>
</div>

<p>Remove the example App files, as we&#8217;ll be adding our own files soon:</p>

<div>
<div>
<pre>rm src/main/java/example/bean/guice/App.java
rm src/test/java/example/bean/guice/AppTest.java</pre>
</div>
</div>

<p>Now edit the POM, first we need to add a dependency to the <tt>guice-bean-inject</tt> library:</p>

<div>
<div><strong>pom.xml</strong></div>
<div>
<pre>  &lt;dependencies&gt;
    &lt;!-- ... --&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.sonatype.spice.inject&lt;/groupId&gt;
      &lt;artifactId&gt;guice-bean-inject&lt;/artifactId&gt;
      &lt;version&gt;0.1.0&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;!-- ... --&gt;
  &lt;/dependencies&gt;</pre>
</div>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>This will also pull in the <tt>guice-bean-reflect</tt> and <tt>guice-patches</tt> libraries</td>
</tr>
</tbody>
</table>
</div>

<p>We also need to tell Maven to compile at the Java5 level, because this is the minimum required by Guice:</p>

<div>
<div><strong>pom.xml</strong></div>
<div>
<pre>  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
        &lt;configuration&gt;
          &lt;source&gt;1.5&lt;/source&gt;
          &lt;target&gt;1.5&lt;/target&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;</pre>
</div>
</div>

<p>We&#8217;re now ready to add our example code, let&#8217;s start with a very simple &#8220;do nothing&#8221; binder:</p>

<div>
<div><strong>src/main/java/example/bean/guice/SimpleBeanBinder.java</strong></div>
<div>
<pre>package example.bean.guice;

import org.sonatype.guice.bean.inject.BeanBinder;
import org.sonatype.guice.bean.inject.PropertyBinder;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;

public class SimpleBeanBinder
  implements BeanBinder
{
  public &lt;B&gt; PropertyBinder bindBean( TypeLiteral&lt;B&gt; type, TypeEncounter&lt;B&gt; encounter )
  {
    return null;
  }
}</pre>
</div>
</div>

<p>Well that&#8217;s fairly useless! We should at least return some property binders which in turn return some property bindings, otherwise nothing will be injected. To save on typing we&#8217;ll put our injection code in a couple of nested anonymous classes, but we could just as well have created named classes. Let&#8217;s also use the bean property to do the actual injection (for the moment we will just inject <tt>null</tt>).</p>

<div>
<div><strong>src/main/java/example/bean/guice/SimpleBeanBinder.java</strong></div>
<div>
<pre>package example.bean.guice;

import org.sonatype.guice.bean.inject.BeanBinder;
import org.sonatype.guice.bean.inject.PropertyBinder;
import org.sonatype.guice.bean.inject.PropertyBinding;
import org.sonatype.guice.bean.reflect.BeanProperty;

import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;

public class SimpleBeanBinder
  implements BeanBinder
{
  public &lt;B&gt; PropertyBinder bindBean( TypeLiteral&lt;B&gt; type, TypeEncounter&lt;B&gt; encounter )
  {
    return new PropertyBinder()
    {
      public &lt;T&gt; PropertyBinding bindProperty( final BeanProperty&lt;T&gt; property )
      {
        return new PropertyBinding()
        {
          public &lt;C&gt; void injectProperty( C bean )
          {
            property.set( bean, null );
          }
        };
      }
    };
  }
}</pre>
</div>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>We made the <tt>property</tt> parameter <tt>final</tt> so we could use it inside the anonymous class</td>
</tr>
</tbody>
</table>
</div>

<p>Next we need to provide actual values for our bean properties. We&#8217;re free to get these values from anywhere we want, but to keep this example simple we&#8217;ll just get them from the Guice injector. So how do we access the injector while we&#8217;re still configuring bindings? Well the <tt>TypeEncounter</tt> has methods to look up the <tt>Provider</tt> for a given binding <tt>Key</tt>. But be careful &#8211; we can&#8217;t use these providers during the property binding call because the injector is still being initialized. We can only use them once the injection phase starts, such as in the <tt>injectProperty</tt> method.</p>

<p>Our example bean binder takes the simple name of the bean class, appends the property name, and turns it into a JSR 330 binding annotation like <tt>@Named("PersonBean.name")</tt>. <em>In practice you&#8217;ll also want to include the package name to avoid collisions.</em> The appropriate value provider is supplied by the <tt>TypeEncounter</tt> using a key based on the binding annotation and property type. We store the provider in a final variable so we can access it later on when we need to inject the property value into a bean.</p>

<div>
<div><strong>src/main/java/example/bean/guice/SimpleBeanBinder.java</strong></div>
<div>
<pre>package example.bean.guice;

import javax.inject.Named;
import javax.inject.Provider;

import org.sonatype.guice.bean.inject.BeanBinder;
import org.sonatype.guice.bean.inject.PropertyBinder;
import org.sonatype.guice.bean.inject.PropertyBinding;
import org.sonatype.guice.bean.reflect.BeanProperty;

import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.util.Jsr330;

public class SimpleBeanBinder
  implements BeanBinder
{
  public &lt;B1&gt; PropertyBinder bindBean( final TypeLiteral&lt;B1&gt; type, final TypeEncounter&lt;B1&gt; encounter )
  {
    return new PropertyBinder()
    {
      public &lt;T&gt; PropertyBinding bindProperty( final BeanProperty&lt;T&gt; property )
      {
        // simple mapping id, not guaranteed to be unique as we don't include the package namespace
        Named valueId = Jsr330.named( type.getRawType().getSimpleName() + "." + property.getName() );
        final Provider&lt;T&gt; valueProvider = encounter.getProvider( Key.get( property.getType(), valueId ) );

        return new PropertyBinding()
        {
          public &lt;C&gt; void injectProperty( C bean )
          {
            property.set( bean, valueProvider.get());
          }
        };
      }
    };
  }
}</pre>
</div>
</div>

<p>We now have a working bean binder that maps bean properties to JSR 330 named bindings. To finish things off, let&#8217;s add a bit of logging so we can see what the binder is doing during the test:</p>

<div>
<div><strong>src/main/java/example/bean/guice/SimpleBeanBinder.java</strong></div>
<div>
<pre>package example.bean.guice;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Named;
import javax.inject.Provider;

import org.sonatype.guice.bean.inject.BeanBinder;
import org.sonatype.guice.bean.inject.PropertyBinder;
import org.sonatype.guice.bean.inject.PropertyBinding;
import org.sonatype.guice.bean.reflect.BeanProperty;

import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.spi.TypeEncounter;
import com.google.inject.util.Jsr330;

public class SimpleBeanBinder
  implements BeanBinder
{
  private final Logger LOGGER = Logger.getLogger( SimpleBeanBinder.class.getName() );

  void log( String message )
  {
    // blank method+class to remove clutter <img src='http://blog.sonatype.com/people/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> 
    LOGGER.logp( Level.INFO, "", "", message );
  }

  public &lt;B1&gt; PropertyBinder bindBean( final TypeLiteral&lt;B1&gt; type, final TypeEncounter&lt;B1&gt; encounter )
  {
    log( "Binding bean &lt;" + type + "&gt;" );
    return new PropertyBinder()
    {
      public &lt;T&gt; PropertyBinding bindProperty( final BeanProperty&lt;T&gt; property )
      {
        log( "Binding property [" + property.getName() + "]" );

        // simple mapping id, not guaranteed to be unique as we don't include the package namespace
        Named valueId = Jsr330.named( type.getRawType().getSimpleName() + "." + property.getName() );
        final Provider&lt;T&gt; valueProvider = encounter.getProvider( Key.get( property.getType(), valueId ) );

        return new PropertyBinding()
        {
          public &lt;C&gt; void injectProperty( C bean )
          {
            T value = valueProvider.get();
            log( "Injecting property [" + property.getName() + "] with \"" + value + "\"" );
            property.set( bean, value );
          }
        };
      }
    };
  }
}</pre>
</div>
</div>

<p>OK so we have our simple bean binder, now we need a bean to test it with. How about the following:</p>

<div>
<div><strong>src/main/java/example/bean/guice/PersonBean.java</strong></div>
<div>
<pre>package example.bean.guice;

public class PersonBean
{
  private int age;

  private String name;

  public void setName( String name )
  {
    this.name = name.toUpperCase();
  }

  public String getName()
  {
    return name;
  }

  public int getAge()
  {
    return age;
  }
}</pre>
</div>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/forbidden.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>This is a trivial bean that mixes field and setter injection, it is definitely not meant to represent good coding practice!</td>
</tr>
</tbody>
</table>
</div>

<p>Finally we need to write a test that exercises our bean binder. The following jUnit test bootstraps a Guice injector that uses our binder along with a couple of constant bindings for each of the bean properties. Guice will handle converting the constant strings to the right types. The injector is used to inject the example bean instance into the test, where its properties are checked against the expected values.</p>

<div>
<div><strong>src/test/java/example/bean/guice/PersonBeanTest.java</strong></div>
<div>
<pre>package example.bean.guice;

import javax.inject.Inject;

import junit.framework.TestCase;

import org.sonatype.guice.bean.inject.BeanListener;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.util.Jsr330;

public class PersonBeanTest
  extends TestCase
{
  @Inject
  PersonBean personBean;

  @Override
  protected void setUp()
  {
    Guice.createInjector( new AbstractModule()
    {
      @Override
      protected void configure()
      {
        bindListener( Matchers.only( TypeLiteral.get( PersonBean.class ) ),
                      new BeanListener( new SimpleBeanBinder() ) );

        bindConstant().annotatedWith( Jsr330.named( "PersonBean.name" ) ).to( "John Smith" );
        bindConstant().annotatedWith( Jsr330.named( "PersonBean.age" ) ).to( "42" );
      }
    } ).injectMembers( this );
  }

  public void testNameBean()
  {
    // check the name was capitalized by the setter
    assertEquals( "JOHN SMITH", personBean.getName() );
    assertEquals( 42, personBean.getAge() );
  }
}</pre>
</div>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>If you are doing a lot of Guice testing, you should take a look at the <a rel="nofollow" href="http://code.google.com/p/atunit/">atunit<sup><img src="https://docs.sonatype.com/images/icons/linkext7.gif" border="0" alt="" width="7" height="7" align="absmiddle" /></sup></a> library</td>
</tr>
</tbody>
</table>
</div>

<p>We&#8217;re now ready to test our example bean binder! Type the following command to kick things off:</p>

<div>
<div>
<pre>mvn clean install</pre>
</div>
</div>

<p>You should see the usual Maven output followed by a successful test, which should look something like this:</p>

<div>
<div>
<pre>-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running example.bean.guice.PersonBeanTest
Jan 8, 2010 12:27:07 AM
INFO: Binding bean &lt;example.bean.guice.PersonBean&gt;
Jan 8, 2010 12:27:08 AM
INFO: Binding property [name]
Jan 8, 2010 12:27:08 AM
INFO: Binding property [age]
Jan 8, 2010 12:27:08 AM
INFO: Injecting property [age] with "42"
Jan 8, 2010 12:27:08 AM
INFO: Injecting property [name] with "John Smith"
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.785 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0</pre>
</div>
</div>

<p>Congratulations, you&#8217;ve just used Guice to initialize a plain old bean with no annotations at all!</p>

<h3>Next: Reflection</h3>

<p>Interested in how the <tt>BeanListener</tt> finds bean properties? We&#8217;ll take a closer look at this in the next post in this series which will cover Generic Bean reflection.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-3-creating-a-guice-bean-extension-layer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>From Plexus to Guice (#2): The Guice/Plexus Bridge and Custom Bean Injection</title>
		<link>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-2-the-guiceplexus-bridge-and-custom-bean-injection/</link>
		<comments>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-2-the-guiceplexus-bridge-and-custom-bean-injection/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 08:00:05 +0000</pubDate>
		<dc:creator>Stuart McCulloch</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[Sonatype]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[pom]]></category>

		<guid isPermaLink="false">http://www.sonatype.com/people/?p=3947</guid>
		<description><![CDATA[In the next few articles of the &#8220;Plexus to Guice&#8221; series I will look at the modular design of our replacement Plexus container and show how you can configure a POB (Plain Old Bean) from Guice with a simple code example. In the first article of this series, Jason discussed the need to move to [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/01/from-plexus-to-guice1.png"><img class="alignright size-full wp-image-4024" title="from-plexus-to-guice" src="http://www.sonatype.com/people/wp-content/uploads/2010/01/from-plexus-to-guice1.png" alt="" width="250" height="62" /></a>In the next few articles of the &#8220;Plexus to Guice&#8221; series I will look at the modular design of our replacement Plexus container and show how you can configure a POB (Plain Old Bean) from Guice with a simple code example.   In the <a href="http://www.sonatype.com/people/2010/01/from-plexus-to-guice-1-why-guice/">first article</a> of this series, Jason discussed the need to move to a more widely used and support container, and the reasons why we chose to standardize on Guice.   As we migrate more Plexus-based applications (such as Maven) to Guice, we still to maintain backward-compatibility for all of the plugins and extensions which were developed using Plexus.  In this post, I start to discuss the scope and initial efforts to create something we&#8217;re calling the Guice/Plexus &#8220;shim&#8221;.   It is a library, a &#8220;container&#8221; that was developed to allow existing Plexus components to use Guice under the hood without any modification. <span id="more-3947"></span></p>

<h3>Scope, Architecture, and Conventions</h3>

<p>Our goal is to create a swap-in replacement for <a href="http://plexus.codehaus.org/plexus-containers/plexus-container-default/">Plexus</a> built on top of <a href="http://code.google.com/p/google-guice/">Guice</a>. Ideally this should be done without changing the core Guice code, but if this is not possible then any fixes or new functionality should be written up and reported on the Guice <a href="http://code.google.com/p/google-guice/issues/list">issues</a> page.   While there is no guarantee that these changes will make it into an official Guice release, improvements that benefit a wider audience should have a better chance of making it into Guice.</p>

<p>Sonatype currently maintains a <a href="http://svn.sonatype.org/spice/trunk/spice-inject/guice-patches">patched build</a> of Guice trunk with the following major patches:</p>

<ul>
    <li><a href="http://code.google.com/p/google-guice/issues/detail?id=436">Provide access to Guice&#8217;s own internal TypeConverters</a></li>
    <li><a href="http://code.google.com/p/google-guice/issues/detail?id=343">BytecodeGen and related AOP / bridge classloader fixes</a></li>
</ul>

<p>This build also contains some experimental changes which have not yet been written up because they are still being tested:</p>

<ul>
    <li>ability to turn off validation error about using @Singleton on an interface instead of an implementation class</li>
    <li>ability to turn off creation of parent JIT bindings when using child injectors (simplified version of <a rel="nofollow" href="http://code.google.com/p/google-guice/issues/detail?id=342">this issue</a>)</li>
</ul>

<h3>Guice/Plexus Integration Module Architecture</h3>

<p>The solution is separated into re-usable, pluggable modules that together provide a replacement for the existing Plexus container. There is also an artifact that combines these modules into a single JAR, as this would make it easier to swap between the old and new container. Each module has a specific responsibility and any dependencies between modules is kept at a minimum.   The following is a list of the components or modules that comprise the Guice/Plexus integration project.</p>

<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/01/guice-plexus-shim.png"><img class="size-full wp-image-3951 alignright" title="guice-plexus-shim" src="http://www.sonatype.com/people/wp-content/uploads/2010/01/guice-plexus-shim.png" alt="" width="337" height="301" /></a></p>

<dl> <dt>guice-bean-inject</dt> <dd>Extends Guice to support customized injection of named properties (fields and setter methods).</dd> <dt>guice-bean-reflect</dt> <dd>Provides utility methods and support code for reflection, bean properties, and resource scanning.</dd> <dt>guice-plexus-metadata</dt> <dd>Shared metadata interfaces, runtime implementations of Plexus annotations, and collection adapters.</dd> <dt>guice-plexus-scanners</dt> <dd>Annotation and XML scanners that provide metadata about components, requirements, and configuration.</dd> <dt>guice-plexus-converters</dt> <dd>Standard Plexus type conversion rules that can create instances from simple strings and XML markup.</dd> <dt>guice-plexus-locators</dt> <dd>Guice based registry that can locate components of a certain type, optionally ordered by name hints.</dd> <dt>guice-plexus-bindings</dt> <dd>Guice <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Module.html">module</a> that uses: scanners to find and bind Plexus component beans, converters to turn configurations into instances, and locators to find components based on requirements. This component also provides a simple lifecycle management API.</dd> <dt>guice-plexus-shim</dt> <dd>Creates an <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Injector.html">injector</a> with Plexus bean support, adds Plexus lifecycles, and provides the container API.</dd> </dl>

<h2>A Brief introduction to Guice and JSR330</h2>

<p><a rel="nofollow" href="http://code.google.com/p/google-guice/">Guice</a> is a <a rel="nofollow" href="http://martinfowler.com/articles/injection.html">Dependency Injection</a> framework that injects constructors, methods, and fields annotated with @Inject. Guice recognizes both the <a rel="nofollow" href="http://atinject.googlecode.com/svn/trunk/javadoc/javax/inject/Inject.html">JSR 330</a> and the original <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/Inject.html">Guice</a> form of this annotation.</p>

<p>Every injection point (constructor, method, or field) has a number of dependencies, each one represented by a key: the type to be injected plus an optional qualifier annotation that lets you choose between different implementations of the same type. For example:</p>

<div>
<div>
<pre>public class Car {
   // Injectable constructor
   @Inject public Car(Engine engine) { ... }

   // Injectable field
   @Inject @Named("Corinthian Leather") private Seat seat;

   // Injectable package-private method
   @Inject void install(Windshield windshield, Trunk trunk) { ... }
}</pre>
</div>
</div>

<p>Has the following injection points and dependency keys:</p>

<div>
<div>
<pre>Constructor      ---&gt; Key[ Engine ]
Field "seat"     ---&gt; Key[ Seat, @Named( "Corinthian Leather" ) ]
Method "install" ---&gt; Key[ Windshield ], Key[ Trunk ]</pre>
</div>
</div>

<p>The Guice injector maintains a set of bindings that map dependency keys to <a rel="nofollow" href="http://atinject.googlecode.com/svn/trunk/javadoc/javax/inject/Provider.html">providers</a> that supply instances of the key type. These providers may use different strategies to supply instances: per-lookup, singleton, per-conversation, even your own custom strategies.</p>

<p>When you configure Guice you are registering bindings from one key to another, or between keys and providers:</p>

<div>
<div>
<pre>// Key[ Seat ] ---&gt; Key[ FoamSeatImpl ]
bind( Seat.class ).to( FoamSeatImpl.class );

// Key[ Seat, @Named( "Corinthian Leather" ) ] ---&gt; Key[ LeatherSeatImpl ]
bind( Seat.class ).annotatedWith( Names.named( "Corinthian Leather" ) ).to( LeatherSeatImpl.class );

// Key[ Engine ] ---&gt; Key[ V8EngineImpl ]
bind( Engine.class ).to( V8EngineImpl.class );

// Key[ V8EngineImpl ] ---&gt; Provider[ V8EngineImpl, "singleton" ]
bind( V8EngineImpl.class ).in( Singleton.class );

// Key[ Windshield ] ---&gt; Provider[ Windshield, "custom" ]
bind( Windshield.class ).toProvider( WindshieldProvider.class );

// Key[ Trunk ] ---&gt; Provider[ TrunkImpl, "constant" ]
bind( Trunk.class ).toInstance( new TrunkImpl() );</pre>
</div>
</div>

<p>The injector can also create certain types of bindings on-demand when no such explicit binding already exists, such as:</p>

<div>
<div>
<pre>// Key[ FoamSeatImpl ] ---&gt; Provider[ FoamSeatImpl , "per-lookup" ]
// Key[ LeatherSeatImpl] ---&gt; Provider[ LeatherSeatImpl, "per-lookup" ]</pre>
</div>
</div>

<div>
<table><colgroup> <col width="24"></col> <col></col> </colgroup>
<tbody>
<tr>
<td valign="top"><img src="https://docs.sonatype.com/images/icons/emoticons/information.gif" border="0" alt="" width="16" height="16" align="absmiddle" /></td>
<td>The <tt>Key[...]</tt> and <tt>Provider[...]</tt> markup is pseudo-code</td>
</tr>
</tbody>
</table>
</div>

<p>So far so good, but what if you have classes that don&#8217;t mark dependencies with <tt>@Inject</tt>? What if they&#8217;re identified in XML or marked with custom annotations like <tt>@Requirement</tt> or <tt>@Configuration</tt>?</p>

<h2>TypeListeners, MembersInjectors, and InjectionListeners</h2>

<p>Since 2.0 Guice has provided a way to supplement the core injection process with your own <a rel="nofollow" href="http://code.google.com/p/google-guice/wiki/CustomInjections">custom injections</a>. Here&#8217;s what you need to do:</p>

<ol>
    <li>Register your custom <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/spi/TypeListener.html">TypeListener</a>, using a <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/matcher/Matcher.html">Matcher</a> to filter the specific types you are interested in, or <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/matcher/Matchers.html">Matchers.any()</a> if you want to process all types</li>
    <li>Guice will call your TypeListener once for each type that matches your chosen matcher, passing you a <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/spi/TypeEncounter.html">TypeEncounter</a></li>
    <li>You can then analyze the type to be injected, prepare any custom injection data, and use the TypeEncounter to register a<a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/MembersInjector.html">MembersInjector</a> or <a rel="nofollow" href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/spi/InjectionListener.html">InjectionListener</a> for this type. Because the TypeListener is called per-type, and not per-instance, you should try to do as much preparation work here as possible to avoid spending too much time in the MembersInjector or InjectionListener</li>
    <li>Guice will call your MembersInjector once for each instance it injects, after it has performed the core injection. You can then use the data prepared by your TypeListener to perform any custom injection</li>
    <li>Finally Guice will call your InjectionListener once for each instance it injects, after all injections are complete. This is where you can hook in management code, such as start and stop life-cycle support</li>
</ol>

<p><a href="http://www.sonatype.com/people/wp-content/uploads/2010/01/custom-injection.png"><img class="aligncenter size-full wp-image-4032" title="custom-injection" src="http://www.sonatype.com/people/wp-content/uploads/2010/01/custom-injection.png" alt="" width="349" height="301" /></a></p>

<p>You&#8217;ll notice that Guice does not dictate how each type should be scanned or prepared for custom injection. While Guice does provide utility methods that can tell you which class members are annotated with @Inject, there&#8217;s no general-purpose mechanism to scan class members looking for custom annotations. On the one hand this is good, because it avoids bloating the core JAR with code you might not need. But on the other hand each custom injection client could end up implementing similar scanning code again and again. The recommended approach is to put optional code like this in an extension library that people can use if they need to, rather than keep folding it into the core.</p>

<p>We&#8217;re going to use custom injection to support Plexus components whose dependencies may be annotated or configured in XML. Plexus components are similar to Java beans in that they can have fields or setter methods, so rather than write a custom injector that&#8217;s closely tied to Plexus let&#8217;s see if we can develop an extension library for &#8220;beans&#8221; in general. That way we can build support for Plexus on top of it, and allow people to re-use it for other bean-style injections.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sonatype.com/people/2010/01/from-plexus-to-guice-2-the-guiceplexus-bridge-and-custom-bean-injection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
