<?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>Source Allies Blog &#187; Spring</title>
	<atom:link href="http://blogs.sourceallies.com/tag/spring/feed/" rel="self" type="application/rss+xml" />
	<link>http://blogs.sourceallies.com</link>
	<description>Technical and process thinking from Source Allies employees</description>
	<lastBuildDate>Mon, 06 Feb 2012 17:40:03 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Spring Injection with @Resource, @Autowired and @Inject</title>
		<link>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/</link>
		<comments>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 12:00:09 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[@Autowired]]></category>
		<category><![CDATA[@Inject]]></category>
		<category><![CDATA[@Resource]]></category>
		<category><![CDATA[Injection]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2350</guid>
		<description><![CDATA[Overview
I&#8217;ve been asked several times to explain the difference between injecting Spring beans with &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217;.  While I received a few opinions from colleagues and read a couple of posts on this topic I didn&#8217;t feel like I had a complete picture.
Annotations


Annotation
Package
Source


@Resource
javax.annotation
Java


@Inject
javax.inject
Java


@Qualifier
javax.inject
Java


@Autowired
org.springframework.bean.factory
Spring



In order to explore the behavior of each annotation I fired [...]]]></description>
			<content:encoded><![CDATA[<h2>Overview</h2>
<p>I&#8217;ve been asked several times to explain the difference between injecting Spring beans with &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217;.  While I received a few opinions from colleagues and read a couple of posts on this topic I didn&#8217;t feel like I had a complete picture.</p>
<h4>Annotations</h4>
<table>
<tr>
<th>Annotation</th>
<th>Package</th>
<th>Source</th>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Resource</td>
<td style="text-align:left; padding-left:5px;">javax.annotation</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Inject</td>
<td style="text-align:left; padding-left:5px;">javax.inject</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Qualifier</td>
<td style="text-align:left; padding-left:5px;">javax.inject</td>
<td style="text-align:left; padding-left:5px;">Java</td>
</tr>
<tr>
<td style="text-align:left; padding-left:5px;">@Autowired</td>
<td style="text-align:left; padding-left:5px;">org.springframework.bean.factory</td>
<td style="text-align:left; padding-left:5px;">Spring</td>
</tr>
</table>
<p><br/><br />
In order to explore the behavior of each annotation I fired up <a href="http://www.springsource.com/developer/sts">Spring Tool Suite</a> and started debugging the code.  I used Spring 3.0.5.RELEASE in my research. The following is a summary of my findings.<br />
<span id="more-2350"></span></p>
<h2>The Code</h2>
<p>I wanted to know how &#8216;@Resource&#8217;, &#8216;@Autowired&#8217;, and &#8216;@Inject&#8217; resolved dependencies.  I created an interface called &#8216;Party&#8217; and created two implementations classes.  This allowed me to inject beans without using the concrete type.  This provided the flexibility I needed to determine how Spring resolves beans when there are multiple type matches.</p>

<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> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8216;Person&#8217; is a component and it implements &#8216;Party&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.person</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8216;Organization&#8217; is a component and it implements &#8216;Party&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.organization</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Organization <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I setup a Spring context that scans both of these packages for beans marked with &#8216;@Component&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;com.sourceallies.organization&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;context:component-scan</span> <span style="color: #000066;">base-package</span>=<span style="color: #ff0000;">&quot;com.sourceallies.person&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<h2>Tests</h2>
<h3>Test 1: Ambiguous Beans</h3>
<p>In this test I injected a &#8216;Party&#8217; bean that has multiple implementations in the Spring context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>In all three cases a &#8216;NoSuchBeanDefinitionException&#8217; is thrown.  While this exception&#8217;s name implies that no beans were found, the message explains that two beans were found.  All of these annotations result in the same exception.</em></strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">NoSuchBeanDefinitionException</span><span style="color: #339933;">:</span> 
No unique bean of type <span style="color: #009900;">&#91;</span>com.<span style="color: #006633;">sourceallies</span>.<span style="color: #006633;">Party</span><span style="color: #009900;">&#93;</span> is defined<span style="color: #339933;">:</span> 
expected single matching bean but found <span style="color: #cc66cc;">2</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span>organization, person<span style="color: #009900;">&#93;</span></pre></div></div>

<h3>Test 2: Field Name</h3>
<p>In this test I named the Party field person.  By default beans marked with &#8216;@Component&#8217; will have the same name as the class.  Therefore the name of the class &#8216;Person&#8217; is person.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p>&#8216;@Resource&#8217; can also take an optional &#8216;name&#8217; attribute.  This is equivalent to the &#8216;@Resource&#8217; code above.  In this case the field variable name remains &#8216;party&#8217;.  There is no equivalent syntax for &#8216;@Autowired&#8217; or &#8216;@Inject&#8217;.  Instead you would have to use a &#8216;@Qualifier&#8217;.  This syntax will be covered later.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All four of these styles inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 3: Field Type</h3>
<p>In this test I changed the type to be a &#8216;Person&#8217;.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Person party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 4: Default Name Qualifier</h3>
<p>In this test I use a &#8216;@Qualifier&#8217; annotation to point to the default name of the &#8216;Person&#8217; component.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 5: Qualified Name</h3>
<p>I added a &#8216;@Qualifier&#8217; annotation to the &#8216;Person&#8217; class</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.person</span><span style="color: #339933;">;</span>
...
@<span style="color: #003399;">Component</span>
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Person <span style="color: #000000; font-weight: bold;">implements</span> Party <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In this test I use a &#8216;@Qualifier&#8217; annotation to point to the qualified name of the &#8216;Person&#8217; component.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;personBean&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party party<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject the &#8216;Person&#8217; bean.</em></strong></p>
<h3>Test 6: List of Beans</h3>
<p>In this test I inject a list of beans.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> List<span style="color: #339933;">&lt;</span>Party<span style="color: #339933;">&gt;</span> parties<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>All of these annotations inject 2 beans into the list.  This can also be accomplished with a &#8216;@Qualifier&#8217;.  Each bean marked with a specific qualifier will be added to the list.</em></strong></p>
<h3>Test 7: Conflicting messages</h3>
<p>In this test I add a bad &#8216;@Qualifier&#8217; and a matching field name.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;bad&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p><strong><em>In this case the field marked with &#8216;@Resource&#8217; uses the field name and ignores the &#8216;@Qualifier&#8217;.  As a result the &#8216;Person&#8217; bean is injected.</em></strong></p>
<p><strong><em>However the &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; field throw a &#8216;NoSuchBeanDefinitionException&#8217; error because it can not find a bean that matches the &#8216;@Qualifier&#8217;.</em></strong></p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"> org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">NoSuchBeanDefinitionException</span><span style="color: #339933;">:</span> 
No matching bean of type <span style="color: #009900;">&#91;</span>com.<span style="color: #006633;">sourceallies</span>.<span style="color: #006633;">Party</span><span style="color: #009900;">&#93;</span> found <span style="color: #000000; font-weight: bold;">for</span> dependency<span style="color: #339933;">:</span> 
expected at least <span style="color: #cc66cc;">1</span> bean which qualifies as autowire candidate <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #000000; font-weight: bold;">this</span> dependency. 
<span style="color: #006633;">Dependency</span> annotations<span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span>@org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">Autowired</span><span style="color: #009900;">&#40;</span>required<span style="color: #339933;">=</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span>,
@org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">annotation</span>.<span style="color: #006633;">Qualifier</span><span style="color: #009900;">&#40;</span>value<span style="color: #339933;">=</span>bad<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<h2>Conclusions</h2>
<p>With the exception of test 2 &#038; 7 the configuration and outcomes were identical.  When I looked under the hood I determined that the &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; annotation behave identically.  Both of these annotations use the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html">&#8216;AutowiredAnnotationBeanPostProcessor&#8217;</a> to inject dependencies. &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; can be used interchangeable to inject Spring beans.  However the &#8216;@Resource&#8217; annotation uses the <a href="http://static.springsource.org/spring/docs/3.1.0.M2/javadoc-api/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.html">&#8216;CommonAnnotationBeanPostProcessor&#8217;</a> to inject dependencies.  Even though they use different post processor classes they all behave nearly identically.  Below is a summary of their execution paths.</p>
<p><strong>@Autowired and @Inject</strong></p>
<ol>
<li>Matches by Type</li>
<li>Restricts by Qualifiers</li>
<li>Matches by Name</li>
</ol>
<p><strong>@Resource</strong></p>
<ol>
<li>Matches by Name</li>
<li>Matches by Type</li>
<li>Restricts by Qualifiers (ignored if match is found by name)</li>
</ol>
<p>While it could be argued that &#8216;@Resource&#8217; will perform faster by name than &#8216;@Autowired&#8217; and &#8216;@Inject&#8217; it would be negligible.  This isn&#8217;t a sufficient reason to favor one syntax over the others.  I do however favor the &#8216;@Resource&#8217; annotation for it&#8217;s concise notation style.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource<span style="color: #009900;">&#40;</span>name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
@Qualifier<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;person&quot;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>You may argue that they can be equal concise if you use the field name to identify the bean name.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Resource
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Autowired
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Inject
<span style="color: #000000; font-weight: bold;">private</span> Party person<span style="color: #339933;">;</span></pre></div></div>

<p>True enough, but what happens if you want to <a href="http://en.wikipedia.org/wiki/Code_refactoring">refactor</a> your code?  By simply renaming the field name you&#8217;re no longer referring to the same bean.   I recommend the following practices when wiring beans with annotations.</p>
<p><strong>Spring Annotation Style Best Practices</strong></p>
<ol>
<li>Explicitly name your component [@Component("beanName")]</li>
<li>Use &#8216;@Resource&#8217; with the &#8216;name&#8217; attribute [@Resource(name="beanName")]</li>
<li>Avoid &#8216;@Qualifier&#8217; annotations unless you want to create a list of similar beans.  For example you may want to mark a set of rules with a specific &#8216;@Qualifier&#8217; annotation.  This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.</li>
<li>Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"].  While this will result in more component-scan configurations it reduces the chance that you&#8217;ll add unnecessary components to your Spring context.</li>
</ol>
<p>Following these guidelines will increase the readability and stability of your Spring annotation configurations.</p>
<h2>Related Links</h2>
<p><a href="/2011/06/testing-spring-wiring/"> Testing Spring Wiring</a><br />
<a href="http://beanoh.org"> Beanoh Spring Wiring Test Framework</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Testing Spring Wiring</title>
		<link>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/</link>
		<comments>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 17:00:20 +0000</pubDate>
		<dc:creator>David Kessler</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=2045</guid>
		<description><![CDATA[Overview
Spring is an essential part of my technology stack.  I cann&#8217;t image providing quality software that doesn&#8217;t leverage an IoC container.  However, decoupling components requires some amount of configuration.  Whether this is accomplished through annotations or XML, it&#8217;s fairly easy to mess up.  Fixing these missing or incorrect configurations doesn&#8217;t take [...]]]></description>
			<content:encoded><![CDATA[<h1>Overview</h1>
<p><a href="http://en.wikipedia.org/wiki/Spring_Framework" target="_blank">Spring</a> is an essential part of my technology stack.  I cann&#8217;t image providing quality software that doesn&#8217;t leverage an <a href="http://en.wikipedia.org/wiki/Inversion_of_control" target="_blank">IoC</a> container.  However, decoupling components requires some amount of configuration.  Whether this is accomplished through annotations or XML, it&#8217;s fairly easy to mess up.  Fixing these missing or incorrect configurations doesn&#8217;t take very long.  The real question is how quickly can you identify these errors?</p>
<p>This question of how long, is a feedback loop question.  Unfortunately many teams wait until they fire up the application server to see if their Spring context is wired correctly.  This is too late.</p>
<p>One of our clients suffered from this very issue.  Due to environmental constraints they could not run automated, in-container tests that would have identified misconfigured beans.  After repeatedly committing stupid configuration mistakes, I decided that I would write a Spring wiring test.  As I began to write this I encountered five problems.<br />
<span id="more-2045"></span></p>
<h1>Problem 1: Scope</h1>
<p>The first problem that I encountered was that not all of my beans were being created when I loaded my context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@RunWith<span style="color: #009900;">&#40;</span>SpringJUnit4ClassRunner.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
@ContextConfiguration
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SpringWiringTest<span style="color: #009900;">&#123;</span>
&nbsp;
     @Test
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
...</pre></div></div>

<p>I quickly remembered that only beans with the default &#8217;singleton&#8217; scope will be loaded immediately.  The rest of the bean scopes (&#8217;prototype&#8217;, &#8216;request&#8217;, and &#8217;session&#8217;) will not be created until they are requested.  In order to solve this I looped through all of the bean names and retrieved each bean from the context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> names <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinitionNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name <span style="color: #339933;">:</span> names<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>However, when I ran this I got the following error</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">java.<span style="color: #006633;">lang</span>.<span style="color: #003399;">IllegalStateException</span><span style="color: #339933;">:</span> No Scope registered <span style="color: #000000; font-weight: bold;">for</span> scope <span style="color: #0000ff;">'request'</span></pre></div></div>

<p>In order to correct this issue I added the following setup method.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Before
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testCaseSetUp<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     context.<span style="color: #006633;">getBeanFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">registerScope</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;session&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> SessionScope<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     context.<span style="color: #006633;">getBeanFactory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">registerScope</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;request&quot;</span>, <span style="color: #000000; font-weight: bold;">new</span> RequestScope<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     MockHttpServletRequest request <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> MockHttpServletRequest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     ServletRequestAttributes attributes <span style="color: #339933;">=</span>
          <span style="color: #000000; font-weight: bold;">new</span> ServletRequestAttributes<span style="color: #009900;">&#40;</span>request<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     RequestContextHolder.<span style="color: #006633;">setRequestAttributes</span><span style="color: #009900;">&#40;</span>attributes<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I threw in the session scope too just to be safe.</p>
<h1>Problem 2: Abstract Bean Definitions</h1>
<p>The second problem that I had to solve was requesting abstract beans.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">org.<span style="color: #006633;">springframework</span>.<span style="color: #006633;">beans</span>.<span style="color: #006633;">factory</span>.<span style="color: #006633;">BeanIsAbstractException</span><span style="color: #339933;">:</span> <span style="color: #003399;">Error</span> creating bean
with name <span style="color: #0000ff;">'testBean'</span><span style="color: #339933;">:</span> Bean definition is <span style="color: #000000; font-weight: bold;">abstract</span></pre></div></div>

<p>In order to solve this issue I added a check to verify if a bean definition was abstract.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> names <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinitionNames</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> name <span style="color: #339933;">:</span> names<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
     BeanDefinition beanDefinition <span style="color: #339933;">=</span> context.<span style="color: #006633;">getBeanDefinition</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>beanDefinition.<span style="color: #006633;">isAbstract</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
          context.<span style="color: #006633;">getBean</span><span style="color: #009900;">&#40;</span>name<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h1>Problem 3: Mock Beans</h1>
<p>The third issue I found was environment specific beans.  JNDI references are one type of environment specific bean.</p>
<blockquote><p><code>&lt;jee:jndi-lookup id="testBean" jndi-name="jdbc/test"/&gt;</code></p></blockquote>
<p>In order to solve this issue, I decided to create a test bootstrap context that imported all of the production contexts.  This provided a place for me to override beans that I wanted to create for the test.  I used Mockito to create mock beans in most situations.</p>
<blockquote><p><code>&lt;bean id="testBean" class="org.mockito.Mockito" factory-method="mock"&gt;<br />
&lt;constructor-arg value="com.something.Foo" /&gt;<br />
&lt;/bean&gt;</code></p></blockquote>
<p>While this worked for most beans, I received errors when I wired up mock DataSources.  Instead I used embedded databases to replace real DataSources.</p>
<blockquote><p><code>&lt;bean id="testDataSource"<br />
class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean"<br />
p:databaseType="H2"<br />
abstract="true"/&gt;</code></p></blockquote>
<h1>Problem 4: Components</h1>
<p>This fourth issue was harder to identify but equally problematic.  I frequently wired up beans with the @Component annotation and failed to configure an &#8216;component-scan&#8217; for those packages.</p>
<blockquote><p><code>&lt;context:component-scan base-package="com.sourceallies"/&gt;</code></p></blockquote>
<p>In other words I needed to reconcile the classes marked with the @Component annotation with the beans that were available in the Spring context.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">ClassPathScanningCandidateComponentProvider scanner <span style="color: #339933;">=</span>
     <span style="color: #000000; font-weight: bold;">new</span> ClassPathScanningCandidateComponentProvider<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
scanner.<span style="color: #006633;">addIncludeFilter</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> AnnotationTypeFilter<span style="color: #009900;">&#40;</span><span style="color: #003399;">Component</span>.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>BeanDefinition bean <span style="color: #339933;">:</span> scanner.<span style="color: #006633;">findCandidateComponents</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;com.something&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      components.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>bean.<span style="color: #006633;">getBeanClassName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This will create a list of components found on the classpath under the specified base package.  Reconciling this list with the beans loaded in the Spring context will identify any components that are not configured in Spring.  This list came in handy for two reasons.  First it identified any components that I needed to configure in Spring.  Second it listed components that were provided in dependent jars.  This list helped us become proactive instead of reactive.</p>
<h1>Problem 5: Duplicate Bean Definitions</h1>
<p>The fifth issue is duplicate bean definitions.  This can occur when more than one bean has the same bean definition name.  This can also occur when the same context is loaded multiple times.  By default Spring allows the new bean definition to overwrite the previous one.  This sounds annoying but harmless.  On the contrary, Spring does not guarantee the loading order.  Furthermore, each deployment environment&#8217;s classloader can load context files in a different order.  The bottom line is that duplicate bean definitions can result in subtle and painful bugs.</p>
<p>While this issue was clear to me the solution was a bit more illusive.  At first I tried to set the allowBeanDefinitionOverriding flag on org.springframework.beans.factory.support.DefaultListableBeanFactory.  This throws an exception if the same bean definition is loaded multiple times.  Case closed, right?</p>
<p>Unfortunately the solution was not this simple.  Problem 3, Mock Beans, requires the creation of a test bootstrap context that overrides bean definitions.  So the allowBeanDefinitionOverriding flag is out.  After crying a little, I started exploring Spring.  Long story short, I overrode the  &#8216;protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)&#8217; method on org.springframework.context.support.ClassPathXmlApplicationContext and injected a delegating proxy.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> loadBeanDefinitions<span style="color: #009900;">&#40;</span>DefaultListableBeanFactory beanFactory<span style="color: #009900;">&#41;</span>
		<span style="color: #000000; font-weight: bold;">throws</span> BeansException, <span style="color: #003399;">IOException</span> <span style="color: #009900;">&#123;</span>
	Enhancer enhancer <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Enhancer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	enhancer.<span style="color: #006633;">setSuperclass</span><span style="color: #009900;">&#40;</span>DefaultListableBeanFactory.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	BeanohBeanFactoryMethodInterceptor callback <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> BeanohBeanFactoryMethodInterceptor<span style="color: #009900;">&#40;</span>
			beanFactory<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	callbacks.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	enhancer.<span style="color: #006633;">setCallback</span><span style="color: #009900;">&#40;</span>callback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	DefaultListableBeanFactory proxy <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>DefaultListableBeanFactory<span style="color: #009900;">&#41;</span> enhancer
			.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">loadBeanDefinitions</span><span style="color: #009900;">&#40;</span>proxy<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>I used &#8216;net.sf.cglib.proxy.Enhancer&#8217; and &#8216;net.sf.cglib.proxy.MethodInterceptor&#8217; to create a proxy.  The trick was to delegate to the real &#8216;org.springframework.beans.factory.support.DefaultListableBeanFactory&#8217; instance.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">@Override
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> intercept<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> object, <span style="color: #003399;">Method</span> method, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args,
		MethodProxy methodProxy<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Throwable</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #003399;">Method</span> delegateMethod <span style="color: #339933;">=</span> delegateClass.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span>method.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>,
			method.<span style="color: #006633;">getParameterTypes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;registerBeanDefinition&quot;</span>.<span style="color: #006633;">equals</span><span style="color: #009900;">&#40;</span>method.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>beanDefinitionMap.<span style="color: #006633;">containsKey</span><span style="color: #009900;">&#40;</span>args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">List</span> definitions <span style="color: #339933;">=</span> beanDefinitionMap
					.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			definitions.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>BeanDefinition<span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #003399;">List</span> beanDefinitions <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ArrayList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			beanDefinitions.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>BeanDefinition<span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			beanDefinitionMap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#41;</span> args<span style="color: #009900;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #009900;">&#93;</span>, beanDefinitions<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000000; font-weight: bold;">return</span> delegateMethod.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>delegate, args<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This passively collects bean definitions that are registered with the registerBeanDefinition method.  This method takes two arguments: a String bean name (arg[0]) and a &#8216;org.springframework.beans.factory.config.BeanDefinition&#8217; (arg[1]).  This map of bean definitions can be inspected later to determine if beans were loaded multiple times.</p>
<h1>Conclusions</h1>
<p>This experience has lead our team to develop a complete, open source solution called <a href="http://beanoh.org">Beanoh</a> (pronounced \&#8217;beanˌō\).  Simply <a href="http://search.maven.org/remotecontent?filepath=com/sourceallies/beanoh/beanoh/1.0.0/beanoh-1.0.0.jar">download</a> the jar or build the project with maven and start using it.</p>

<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> SomeTest <span style="color: #000000; font-weight: bold;">extends</span> BeanohTestCase <span style="color: #009900;">&#123;</span>
&nbsp;
	@Test
	<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> testSomething<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		assertContextLoading<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>For more information visit <a href="http://beanoh.org/overview.html">http://beanoh.org/overview.html</a>.</p>
<p>In just a few short weeks this testing approach prevented our team from committing broken Spring configurations.  Furthermore, we took time to evaluate the inherited components that we received through our project dependencies.  This provided valuable insights into our dependency structure and our packaging strategy.</p>
<p>These wiring tests even gave us feedback as we refactored our spring contexts.  We were able to simplify our context files without worrying that we would break something.  We also identified unused and duplicate bean definitions.  Without the quick feedback of this wiring test we would have committed broken changes that effected the whole team.</p>
<p>Automated tests help you manage code behavior rather than allowing code to drive your behavior.  <a href="http://beanoh.org">Download Beanoh</a> today and take control of your Spring configuration.</p>
<p>For more information checkout our YouTube <a href=" http://www.youtube.com/playlist?p=PL7F1B7F11D0D0FB91">video tutorials</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2011/06/testing-spring-wiring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Aggregate MyBatis.NET SqlMaps from Multiple C# Projects</title>
		<link>http://blogs.sourceallies.com/2010/10/aggregate-mybatis-net-sqlmaps-from-multiple-c-projects/</link>
		<comments>http://blogs.sourceallies.com/2010/10/aggregate-mybatis-net-sqlmaps-from-multiple-c-projects/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 15:20:28 +0000</pubDate>
		<dc:creator>Matt Vincent</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[MyBATIS]]></category>
		<category><![CDATA[Spring.NET]]></category>
		<category><![CDATA[aggregate sqlmaps]]></category>
		<category><![CDATA[combine SqlMap.config]]></category>
		<category><![CDATA[iBATIS]]></category>
		<category><![CDATA[iBATIS.NET]]></category>
		<category><![CDATA[MyBatis.NET]]></category>
		<category><![CDATA[NAnt]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=1589</guid>
		<description><![CDATA[Summary
This blog post describes an approach for integrating Spring.NET and MyBatis.NET in a way that lets iBATIS aggregate SqlMap config files from multiple assemblies (a.k.a. assembly scanning) prior to handing out ISqlMapper instances.  Teams setting up new MyBatis.NET/Spring.NET tech stacks might find this useful.

The Problem
Your typical enterprise C# ASP.NET web application will have dependencies [...]]]></description>
			<content:encoded><![CDATA[<h2>Summary</h2>
<p>This blog post describes an approach for integrating Spring.NET and MyBatis.NET in a way that lets iBATIS aggregate SqlMap config files from multiple assemblies (a.k.a. assembly scanning) prior to handing out ISqlMapper instances.  Teams setting up new MyBatis.NET/Spring.NET tech stacks might find this useful.</p>
<p><span id="more-1589"></span></p>
<h2>The Problem</h2>
<p>Your typical enterprise C# ASP.NET web application will have dependencies on multiple C# projects.  Just as best practices with OOAD and Spring support placing our Spring XML configuration files (Spring.NET doesn&#8217;t have attribute based configuration &#8230; yet) alongside our business components (by namespace or project) rather than keeping all Spring config in a giant single file (thereby limiting reusability of specific business components) we can also follow this process with MyBatis configuration files.  This is not out of the box funcationality with MyBatis.NET.  Furthermore, how do you prevent those consuming your C# Project (containing multiple SqlMap config files) from having to know the exact locations of your SqlMap.config files within your assembly?</p>
<div id="attachment_1593" class="wp-caption aligncenter" style="width: 795px"><a href="http://blogs.sourceallies.com/wp-content/uploads/2010/09/MyBATIS-Spring.NET.png"><img class="size-full wp-image-1593" title="MyBATIS-Spring.NET" src="http://blogs.sourceallies.com/wp-content/uploads/2010/09/MyBATIS-Spring.NET.png" alt="A typical enterprise Spring.NET/MyBATIS.NET web app" width="785" height="651" /></a><p class="wp-caption-text">A typical enterprise Spring.NET/MyBATIS.NET web app</p></div>
<p>Wouldn&#8217;t it be nice to have your ASP.NET web application simply discover any new MyBATIS config files when the application starts up?</p>
<p>If you&#8217;re on the bleeding edge with iBATIS 3 beta code, then this is a fairly simple task with psuedo code like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> sqlMaps <span style="color: #008000;">=</span> Inspector.<span style="color: #0000FF;">GetSqlMapsFromAssembly</span><span style="color: #000000;">&#40;</span>
                       “MyCompany.<span style="color: #0000FF;">Domain1</span>”, “<span style="color: #008000;">*</span>.<span style="color: #0000FF;">SqlMaps</span>.<span style="color: #008000;">*</span>.<span style="color: #0000FF;">xml</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            CodeConfigurationInterpreter codeConfig <span style="color: #008000;">=</span>
                        <span style="color: #008000;">new</span> CodeConfigurationInterpreter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            codeConfig.<span style="color: #0000FF;">AddDatabase</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> OracleProvider<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>, “….”<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> map <span style="color: #0600FF;">in</span> sqlMaps<span style="color: #000000;">&#41;</span>
            codeConfig.<span style="color: #0000FF;">AddSqlMap</span><span style="color: #000000;">&#40;</span>map, <span style="color: #0600FF;">true</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>However, for those of us using MyBatis 1.6.x releases in our Spring.NET apps, below is another solution that allows your app to grab all MyBatis.NET config files in a set of dependent C# project.</p>
<h2>The Solution</h2>
<h3>Step 1. &#8211; Let Spring know about your dependent projects:</h3>
<p>Define a class to hold your config locations like this (yes, Spring.Core.IO.Resource would make much more sense then SearchLocation here&#8230;).</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SqlMapsHolder <span style="color: #008000;">:</span> ISqlMapsHolder
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">private</span> List embeddedSqlMapSearchLocations<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// Two part string: the first representing the NAnt style search pattern, the second is the name of the assembly in which to search.</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> List EmbeddedSqlMapSearchLocations
        <span style="color: #000000;">&#123;</span>
            get <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> embeddedSqlMapSearchLocations<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
            set <span style="color: #000000;">&#123;</span> embeddedSqlMapSearchLocations <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// Take a string of the form &quot;*.Sqlmaps.*.xml, MyCompany.Example&quot; and return it's two parts.</span>
        <span style="color: #008080; font-style: italic;">/// a string like &quot;*.Sqlmaps.*.xml, MyCompany.Example&quot;</span>
       <span style="color: #0600FF;">public</span> SearchLocation GetSearchLocation<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> searchLocationString<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> delimiter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #FF0000;">char</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #666666;">','</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
            <span style="color: #FF0000;">string</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> parts <span style="color: #008000;">=</span> searchLocationString.<span style="color: #0000FF;">Split</span><span style="color: #000000;">&#40;</span>delimiter, <span style="color: #FF0000;">2</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> SearchLocation<span style="color: #000000;">&#40;</span>parts<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span>, parts<span style="color: #000000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// Holds the distinct NAnt search pattern and assembly name parts.</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">struct</span> SearchLocation
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">/// NAnt search pattern and Assembly name</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Pattern, Assembly<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// Constructor</span>
        <span style="color: #008080; font-style: italic;">/// NAnt/Ant search pattern (like *.Sqlmaps.*.xml)</span>
        <span style="color: #008080; font-style: italic;">/// Assembly name (like MyCompany.Example)</span>
        <span style="color: #0600FF;">public</span> SearchLocation<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> pattern, <span style="color: #FF0000;">string</span> assembly<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Pattern <span style="color: #008000;">=</span> pattern<span style="color: #008000;">;</span>
            Assembly <span style="color: #008000;">=</span> assembly<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<h3>Step 2. &#8211; Specify your dependent assemblies in your Spring config XML</h3>
<p>The configuration below will tell your application to look in the Party, Account and Policy dependent assemblies for any XML files (which are of course marked as &#8220;Embedded Resources&#8221;) in a folder called SqlMaps (or any other <a href="http://nant.sourceforge.net/">NAnt style syntax</a> you specify) and will pull all of these SqlMaps together before starting up MyBatis. (The SqlMaps you refer to should start with the  tag)</p>
<p>This is what you should place in your Spring Config files to tell your app in which assemblies to look for SqlMap config files.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;object</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;SqlMapsHolder&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;MyCompany.Util.SqlMapsHolder, MyCompany.Util&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>  
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;EmbeddedSqlMapSearchLocations&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>  
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;list</span> <span style="color: #000066;">element-type</span>=<span style="color: #ff0000;">&quot;string&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>*.Sqlmaps.*.xml, MyCompany.Party<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>*.Sqlmaps.*.xml, MyCompany.Account<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>*.Sqlmaps.*.xml, MyCompany.Policy<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/value<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/list<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/property<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/object<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Where these Sqlmap.xml files look like this:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;utf-8&quot;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sqlMap</span> <span style="color: #000066;">namespace</span>=<span style="color: #ff0000;">&quot;MyCompany.Party.Sqlmaps&quot;</span> </span>
<span style="color: #009900;"><span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://ibatis.apache.org/mapping&quot;</span> </span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;alias<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>... <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/alias<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;resultMaps<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>...<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/resultMaps<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;statements<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>...<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/statements<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sqlMap<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h3>Step 3. &#8211; Create your own SqlMapperFactory.</h3>
<p>Let&#8217;s call it ConfiguredMapperFactory.  Here&#8217;s the pseudo-code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #008080; font-style: italic;">///</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Configuration</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">IBatisNet.DataMapper</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Spring.Context</span><span style="color: #008000;">;</span>
    <span style="color: #008080; font-style: italic;">/// Used by Spring to initialize a custom MyBATIS.NET singleton Mapper</span>
    <span style="color: #008080; font-style: italic;">///</span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ConfiguredMapperFactory <span style="color: #008000;">:</span> IConfiguredMapperFactory, IApplicationContextAware
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// An assembly location in the format:  MyASPNETWebApp.SqlMap.Config.Production.SqlMap.config,MyASPNETWebApp.SqlMap</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> ConfigResourceLocation <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// Container responsible for holding the various SqlMap.xml files that will be merged into one XML document before initializing MyBATIS</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> ISqlMapsHolder SqlMapsHolder <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// Singleton instance of our custom MyBatis.NET Mapper</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> ISqlMapper ConfiguredMapperInstance
        <span style="color: #000000;">&#123;</span>
            get
            <span style="color: #000000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// if the MyBatis.NET config files were not specified via Spring</span>
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>ConfigResourceLocation <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">// then fall back on getting the config location from web.config</span>
                    <span style="color: #0600FF;">lock</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>ConfiguredMapper<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                    <span style="color: #000000;">&#123;</span>
                        <span style="color: #FF0000;">string</span> configResourceLocationFromWebConfig <span style="color: #008000;">=</span>
                            ConfigurationSettings.<span style="color: #0000FF;">AppSettings</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;ibatis.net.config.resource.location&quot;</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
                        ConfigResourceLocation <span style="color: #008000;">=</span> configResourceLocationFromWebConfig<span style="color: #008000;">;</span>
                        _configuredMapperInstance <span style="color: #008000;">=</span> ConfiguredMapper.<span style="color: #0000FF;">Instance</span><span style="color: #000000;">&#40;</span>ConfigResourceLocation, SqlMapsHolder, _applicationContext<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
&nbsp;
                <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_configuredMapperInstance <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">// braces left out for brevity</span>
                    <span style="color: #0600FF;">lock</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>ConfiguredMapper<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                        _configuredMapperInstance <span style="color: #008000;">=</span> ConfiguredMapper.<span style="color: #0000FF;">Instance</span><span style="color: #000000;">&#40;</span>ConfigResourceLocation, SqlMapsHolder, _applicationContext<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                <span style="color: #0600FF;">return</span> _configuredMapperInstance<span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #008080; font-style: italic;">/// Getter for the iBATIS.NET ISqlMapper configured based on custom locations of sqlmap.config and providers.config</span>
        <span style="color: #008080; font-style: italic;">///</span>
        <span style="color: #0600FF;">public</span> ISqlMapper GetConfiguredMapperInstance<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> <span style="color: #0600FF;">return</span> ConfiguredMapperInstance<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">private</span> ISqlMapper _configuredMapperInstance<span style="color: #008000;">;</span></pre></div></div>

<h3>Step 4. &#8211; Make a SqlMap Aggregator</h3>
<p>We&#8217;ll also need a class that knows how to package up all of the iBATIS SqlMaps it finds into a single XML doc that&#8217;s fed to MyBATIS:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Merges specified assembly's XML sqlmaps into a SqlMap.config file </span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;  </span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> SqlMapMerger <span style="color: #000000;">&#123;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> DATAMAPPER_NAMESPACE_PREFIX <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;mapper&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> PROVIDERS_NAMESPACE_PREFIX <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;provider&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> MAPPING_NAMESPACE_PREFIX <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;mapping&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> DATAMAPPER_XML_NAMESPACE <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://ibatis.apache.org/dataMapper&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> PROVIDER_XML_NAMESPACE <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://ibatis.apache.org/providers&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> MAPPING_XML_NAMESPACE <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;http://ibatis.apache.org/mapping&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> XML_DATAMAPPER_CONFIG_ROOT <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;sqlMapConfig&quot;</span><span style="color: #008000;">;</span> 
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> XML_SQLMAPS <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;sqlMapConfig/sqlMaps&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Token for xml path to sqlMap elements.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;  </span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> XML_SQLMAP <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;sqlMapConfig/sqlMaps/sqlMap&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">///&lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Merge the additional SqlMaps into the Primary SqlMap.config with which we'll initialize iBATIS.NET </span>
    <span style="color: #008080; font-style: italic;">///&lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">///&lt;param name=&quot;primarySqlMapConfig&quot;&gt;The application specific SqlMap.config file&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">///&lt;param name=&quot;additionalSqlMapXmlFiles&quot;&gt;A container of additional locations in which we'll search for SqlMap XML files&lt;/param&gt;</span>
    <span style="color: #0600FF;">public</span> XmlDocument Merge<span style="color: #000000;">&#40;</span>XmlDocument primarySqlMapConfig, ISqlMapsHolder additionalSqlMapXmlFiles<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
&nbsp;
        XmlNamespaceManager nsManager <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> XmlNamespaceManager<span style="color: #000000;">&#40;</span>primarySqlMapConfig.<span style="color: #0000FF;">NameTable</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
        nsManager.<span style="color: #0000FF;">AddNamespace</span><span style="color: #000000;">&#40;</span>DATAMAPPER_NAMESPACE_PREFIX, DATAMAPPER_XML_NAMESPACE<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        nsManager.<span style="color: #0000FF;">AddNamespace</span><span style="color: #000000;">&#40;</span>PROVIDERS_NAMESPACE_PREFIX, PROVIDER_XML_NAMESPACE<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        nsManager.<span style="color: #0000FF;">AddNamespace</span><span style="color: #000000;">&#40;</span>MAPPING_NAMESPACE_PREFIX, MAPPING_XML_NAMESPACE<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
&nbsp;
        <span style="color: #FF0000;">String</span> mappingPrefix <span style="color: #008000;">=</span> ApplyDataMapperNamespacePrefix<span style="color: #000000;">&#40;</span>XML_SQLMAPS<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
        XmlNode sqlMapsNode <span style="color: #008000;">=</span> primarySqlMapConfig.<span style="color: #0000FF;">SelectSingleNode</span><span style="color: #000000;">&#40;</span>mappingPrefix, nsManager<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// look at each search location (*.Sqlmaps.*.xml, MyCompany.Project)</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span> searchLocation <span style="color: #0600FF;">in</span> additionalSqlMapXmlFiles.<span style="color: #0000FF;">EmbeddedSqlMapSearchLocations</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
            <span style="color: #008080; font-style: italic;">// split it up between the comma </span>
            SearchLocation location <span style="color: #008000;">=</span> additionalSqlMapXmlFiles.<span style="color: #0000FF;">GetSearchLocation</span><span style="color: #000000;">&#40;</span>searchLocation<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
&nbsp;
            <span style="color: #008080; font-style: italic;">// look for matching files in the assembly </span>
            IList matchingSqlMaps <span style="color: #008000;">=</span> AssemblyResourceUtil.<span style="color: #0000FF;">GetMatchingResources</span><span style="color: #000000;">&#40;</span>location.<span style="color: #0000FF;">Assembly</span>, location.<span style="color: #0000FF;">Pattern</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">// add each of these locations to the primary SqlMap.config's &lt;sqlMaps&gt; section like this: </span>
            <span style="color: #008080; font-style: italic;">// &lt;sqlMaps&gt;  </span>
            <span style="color: #008080; font-style: italic;">//     &lt;sqlMap embedded=&quot;MyCompany.Sqlmaps.Party.xml, MyCompany&quot;/&gt;</span>
            <span style="color: #008080; font-style: italic;">// &lt;/sqlMaps&gt;  </span>
            <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">String</span> fullSqlMapXmlFileName <span style="color: #0600FF;">in</span> matchingSqlMaps<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
                <span style="color: #008080; font-style: italic;">// the &quot;extra&quot; SqlMap that we want to integrate into the main one. </span>
                XmlNode newSqlMap <span style="color: #008000;">=</span> primarySqlMapConfig.<span style="color: #0000FF;">CreateNode</span><span style="color: #000000;">&#40;</span>XmlNodeType.<span style="color: #0000FF;">Element</span>, <span style="color: #666666;">&quot;sqlMap&quot;</span>, DATAMAPPER_XML_NAMESPACE<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
                XmlAttribute embeddedLocation <span style="color: #008000;">=</span> primarySqlMapConfig.<span style="color: #0000FF;">CreateAttribute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;embedded&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                embeddedLocation.<span style="color: #0000FF;">Value</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{0},{1}&quot;</span>, fullSqlMapXmlFileName, location.<span style="color: #0000FF;">Assembly</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                newSqlMap.<span style="color: #0000FF;">Attributes</span>.<span style="color: #0000FF;">Append</span><span style="color: #000000;">&#40;</span>embeddedLocation<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> 
                sqlMapsNode.<span style="color: #0000FF;">AppendChild</span><span style="color: #000000;">&#40;</span>newSqlMap<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span>
        <span style="color: #000000;">&#125;</span>
        <span style="color: #0600FF;">return</span> primarySqlMapConfig<span style="color: #008000;">;</span> 
    <span style="color: #000000;">&#125;</span> 
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;  </span>
    <span style="color: #008080; font-style: italic;">/// Apply the dataMapper namespace prefix </span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> ApplyDataMapperNamespacePrefix<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> elementName<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
        <span style="color: #0600FF;">return</span> DATAMAPPER_NAMESPACE_PREFIX <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;:&quot;</span> <span style="color: #008000;">+</span> elementName. <span style="color: #0000FF;">Replace</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;/&quot;</span>, <span style="color: #666666;">&quot;/&quot;</span> <span style="color: #008000;">+</span> DATAMAPPER_NAMESPACE_PREFIX <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;:&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>Step 5. &#8211; Create a Class to Configure MyBatis using multiple SqlMap config files</h3>
<p>Next, create the ConfiguredMapper that application will use to get instances of the MyBatis ISqlMapper:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">using</span> <span style="color: #008080;">System.Xml</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">IBatisNet.Common.Utilities</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">IBatisNet.DataMapper</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">IBatisNet.DataMapper.Configuration</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">using</span> <span style="color: #008080;">Spring.Context</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// </span>
    <span style="color: #008080; font-style: italic;">/// A singleton class to access the SqlMapper defined by the SqlMap.Config</span>
    <span style="color: #008080; font-style: italic;">/// </span>
    <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> ConfiguredMapper
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080;">#region Fields</span>
        <span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> volatile ISqlMapper _mapper <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
        <span style="color: #008080;">#endregion</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #008080; font-style: italic;">/// static Configure constructor that can be</span>
        <span style="color: #008080; font-style: italic;">/// used for callback</span>
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #008080; font-style: italic;">///</span>
&nbsp;
        <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Configure<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> obj<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _mapper <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #008080; font-style: italic;">/// Init the 'default' SqlMapper defined by the SqlMap.Config file.</span>
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> InitMapper<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> configResourceLocation, ISqlMapsHolder additionalSqlMapXmlFiles, IApplicationContext applicationContext<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            DomSqlMapBuilder builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DomSqlMapBuilder<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            XmlDocument sqlMapConfig <span style="color: #008000;">=</span> Resources.<span style="color: #0000FF;">GetEmbeddedResourceAsXmlDocument</span><span style="color: #000000;">&#40;</span>configResourceLocation<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// example &quot;MyCompany.SqlMap.Config.Production.SqlMap.config,MyCompany&quot;</span>
            SqlMapMerger merger <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> SqlMapMerger<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            XmlDocument mergedSqlMapConfig <span style="color: #008000;">=</span> merger.<span style="color: #0000FF;">Merge</span><span style="color: #000000;">&#40;</span>sqlMapConfig, additionalSqlMapXmlFiles<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _mapper <span style="color: #008000;">=</span> builder.<span style="color: #0000FF;">Configure</span><span style="color: #000000;">&#40;</span>mergedSqlMapConfig<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">// the commented out code below will be the subject of a subsequent blog article:</span>
            <span style="color: #008080; font-style: italic;">// ManagedConnectionStringDataSource managedConnectionStringDataSource = new ManagedConnectionStringDataSource(_mapper.DataSource);</span>
            <span style="color: #008080; font-style: italic;">// managedConnectionStringDataSource.ApplicationContext = applicationContext;</span>
            <span style="color: #008080; font-style: italic;">// inject our own IDataSource so that we can control what is returned when iBATIS calls IDataSource.ConnectionString</span>
            <span style="color: #008080; font-style: italic;">// _mapper.DataSource = managedConnectionStringDataSource;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #008080; font-style: italic;">/// Get the instance of the SqlMapper defined by the SqlMap.Config file.</span>
        <span style="color: #008080; font-style: italic;">/// </span>
        <span style="color: #008080; font-style: italic;">/// A SqlMapper initalized via the SqlMap.Config file.</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> ISqlMapper Instance<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> configResourceLocation, ISqlMapsHolder additionalSqlMapXmlFiles, IApplicationContext applicationContext<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_mapper <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                <span style="color: #0600FF;">lock</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>SqlMapper<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
                <span style="color: #000000;">&#123;</span>
                    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>_mapper <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">// double-check</span>
                    <span style="color: #000000;">&#123;</span>
                        InitMapper<span style="color: #000000;">&#40;</span>configResourceLocation, additionalSqlMapXmlFiles, applicationContext<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #000000;">&#125;</span>
                <span style="color: #000000;">&#125;</span>
            <span style="color: #000000;">&#125;</span>
            <span style="color: #0600FF;">return</span> _mapper<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<h3>Step 6. &#8211; Wire up your custom Mapper Factory in Spring</h3>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;object</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;ConfiguredMapperFactory&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;MyCompany.Util.Ibatis.ConfiguredMapperFactory,MyCompany.Util&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;ConfigResourceLocation&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;MyASPNETWebApp.Config.SqlMap.config,MyASPNETWebApp&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;SqlMapsHolder&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;SqlMapsHolder&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/object<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;object</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;IbatisSqlMapper&quot;</span> <span style="color: #000066;">factory-method</span>=<span style="color: #ff0000;">&quot;GetConfiguredMapperInstance&quot;</span> <span style="color: #000066;">factory-object</span>=<span style="color: #ff0000;">&quot;ConfiguredMapperFactory&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>

<p>Where the SqlMap.config file you refer to is nothing more than:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></span> 
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sqlMapConfig</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://ibatis.apache.org/dataMapper&quot;</span> </span>
<span style="color: #009900;"><span style="color: #000066;">xmlns:xsi</span>=<span style="color: #ff0000;">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>  
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;proxy_userid&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;************&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;proxy_password&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;************&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">key</span>=<span style="color: #ff0000;">&quot;userid&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;************&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/properties<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;providers</span> <span style="color: #000066;">embedded</span>=<span style="color: #ff0000;">&quot;MyCompany.Util.Config.providers.config,MyCompany.Util&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
    <span style="color: #808080; font-style: italic;">&lt;!-- ==== SqlClient configuration ========= --&gt;</span>  
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;database<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>  
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;provider</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;Oracle Data Provider for .NET&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>  
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dataSource</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;mycompanydatasource&quot;</span> <span style="color: #000066;">connectionString</span>=<span style="color: #ff0000;">&quot;Proxy User Id=${proxy_userid};Proxy Password=${proxy_password};User Id=${userid}&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>  
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/database<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;sqlMaps<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
        <span style="color: #808080; font-style: italic;">&lt;!-- The SqlMap XML files are now loaded through a Spring-managed Object called SqlMapsHolder --&gt;</span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sqlMaps<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/sqlMapConfig<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h3>Step 7. &#8211; Inject the IbatisSqlMapper into your Data Access Objects</h3>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;object</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;MyPartyDAO&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;MyCompany....&quot;</span> <span style="color: #000000; font-weight: bold;">&gt;</span></span>  
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;SqlMapper&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;IbatisSqlMapper&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>  
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/object<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Where SqlMapper is an IBatisNet.DataMapper.ISqlMapper field or property in your Data Access Object.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2010/10/aggregate-mybatis-net-sqlmaps-from-multiple-c-projects/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Environment Specific Properties in Spring</title>
		<link>http://blogs.sourceallies.com/2010/03/environment-specific-properties-in-spring/</link>
		<comments>http://blogs.sourceallies.com/2010/03/environment-specific-properties-in-spring/#comments</comments>
		<pubDate>Mon, 01 Mar 2010 19:10:16 +0000</pubDate>
		<dc:creator>Travis Klotz</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=1190</guid>
		<description><![CDATA[
On many occasions I want to be able to inject environment specific property values into my Spring managed beans.  These may be things like web service endpoints, database URLs, etc.  Values I know for each environment at build time, but I want to use the same WAR/EAR file in each environment.  I [...]]]></description>
			<content:encoded><![CDATA[<p>
On many occasions I want to be able to inject environment specific property values into my Spring managed beans.  These may be things like web service endpoints, database URLs, etc.  Values I know for each environment at build time, but I want to use the same WAR/EAR file in each environment.  I would like to keep the actual values separate from the Spring config files themselves.  And I would really like to manage a set of default values for each property, so that I do not need to specify a value for every property in every environment (ex. my credit card processing URL for dev, test, uat is the same, but for production it is different.)
</p>
<p><span id="more-1190"></span></p>
<p>
Spring already has 90% of this solution already worked out.  The PropertyPlaceholderConfigurer can be used to externalize property values into Java properties files.  These properties can then be referenced &#8220;ant style&#8221; in your configuration files ex. ${myPropertyValues}.  It can even handle multiple files, checking them in order for each property,  so one file can override one or move values that are stored in another.   However the PropertyPlaceholderConfigurer doesn&#8217;t have any concept of an environment specific file.
</p>
<p>
Thats where we come in:
</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">com.sourceallies.config</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.beans.factory.config.PropertyPlaceholderConfigurer</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.core.io.ClassPathResource</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">org.springframework.core.io.Resource</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> EnvironmentPropertyPlaceholderConfigurer <span style="color: #000000; font-weight: bold;">extends</span>
		PropertyPlaceholderConfigurer <span style="color: #009900;">&#123;</span>
&nbsp;
   @Override
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setLocation<span style="color: #009900;">&#40;</span>Resource location<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #009900;">&#40;</span>location <span style="color: #000000; font-weight: bold;">instanceof</span> ClassPathResource<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">RuntimeException</span><span style="color: #009900;">&#40;</span>
               <span style="color: #0000ff;">&quot;EnvironmentPropertyPlaceholderConfigurer &quot;</span> <span style="color: #339933;">+</span> 
               <span style="color: #0000ff;">&quot;locations must be on the classpath&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
&nbsp;
      ClassPathResource cl <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>ClassPathResource<span style="color: #009900;">&#41;</span> location<span style="color: #339933;">;</span>
      <span style="color: #003399;">String</span> filename <span style="color: #339933;">=</span> cl.<span style="color: #006633;">getFilename</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      <span style="color: #666666; font-style: italic;">//switch  &quot;env.properties&quot; to &quot;env.dev.properties&quot;</span>
      <span style="color: #003399;">String</span> envFilename <span style="color: #339933;">=</span> filename.<span style="color: #006633;">replaceAll</span><span style="color: #009900;">&#40;</span>
            <span style="color: #0000ff;">&quot;(.*)<span style="color: #000099; font-weight: bold;">\\</span>.properties&quot;</span>, 
            <span style="color: #0000ff;">&quot;$1.&quot;</span> <span style="color: #339933;">+</span> getEnvironment<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">toLowerCase</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;.properties&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      Resource envLocation <span style="color: #339933;">=</span> cl.<span style="color: #006633;">createRelative</span><span style="color: #009900;">&#40;</span>envFilename<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>envLocation.<span style="color: #006633;">exists</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
         setLocations<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Resource<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> location, envLocation <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
         setLocations<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Resource<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> location <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
   <span style="color: #009900;">&#125;</span>
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getEnvironment<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #666666; font-style: italic;">/*
       * Magic goes here. This method must be able to determine which
       * environment it is running in without any help from injected
       * properties.
       */</span>
&nbsp;
      <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">getProperty</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;sai.env&quot;</span>, <span style="color: #0000ff;">&quot;DEV&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>
This version of the configurer expects a single resource to be passed in via the location property.  In this case I restrict it only to ClassPathResource instances, but really it can be any version that can generate a new resource with a relative path.  The resource we configure here should be the &#8220;default&#8221; file, the configurer will then build an environment specific file based on the default name and check its existence.  If the environment specific file is found the are ordered up so that any properties in the environment file will override the values in the default file.  If no environment file is found, only the default file is used.
</p>
<p>
The only real magic here is how the configurer determines the environment that its running in.  In this simple case, the configurer relies on a system property to tell it what environment its running in.  In larger organizations I have found that getting system properties set reliably across environments to be extremely difficult (most shops still tack on application server administration to the jobs of the DBA&#8217;s or the Unix/Windows admins who are already overworked.)  In these cases, more extreme methods may be needed to determine the environment name.  JNDI lookups, Database queries, reading files from the file system may all be good solutions.  The important thing is that you can&#8217;t inject the environment name,  if it were that easy, we wouldn&#8217;t actually need this configurer!
</p></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2010/03/environment-specific-properties-in-spring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Spring&#8217;s refreshable beans</title>
		<link>http://blogs.sourceallies.com/2010/01/springs-refreshable-beans/</link>
		<comments>http://blogs.sourceallies.com/2010/01/springs-refreshable-beans/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 14:00:19 +0000</pubDate>
		<dc:creator>Octavian Covalschi</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=854</guid>
		<description><![CDATA[A couple of days ago I found out about a really nice feature in Spring, called &#8216;refreshable bean&#8217;.
Spring&#8217;s vision a refreshable bean is a dynamic-language-backed bean that monitors changes to its source code and then reloads itself when changes occur. And it is all this is done without restarting/re-deploying entire app. Sweet!

Currently Spring supports only [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of days ago I found out about a really nice feature in Spring, called &#8216;refreshable bean&#8217;.</p>
<p>Spring&#8217;s vision a refreshable bean is a dynamic-language-backed bean that monitors changes to its source code and then reloads itself when changes occur. And it is all this is done without restarting/re-deploying entire app. Sweet!<br />
<span id="more-854"></span><br />
Currently Spring supports only 3 dynamic languages: JRuby, Groovy, BeanShell.</p>
<p>A simple example taken from springsource&#8217;s website looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
    ...
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;lang:groovy</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;messenger&quot;</span></span>
<span style="color: #009900;">          &lt;!-- switches refreshing on with 5 seconds between checks --<span style="color: #000000; font-weight: bold;">&gt;</span></span>
          refresh-check-delay=&quot;5000&quot; 
          script-source=&quot;classpath:Messenger.groovy&quot;&gt;
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;lang:property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;message&quot;</span> <span style="color: #000066;">value</span>=<span style="color: #ff0000;">&quot;I Can Do The Frug&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/lang:groovy<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;bookingService&quot;</span> <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;x.y.DefaultBookingService&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;messenger&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;messenger&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   ...
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>So, the &#8216;refresh-check-delay&#8217; attribute makes &#8216;messenger&#8217; bean &#8216;refreshable&#8217;. This attribute is the number of milliseconds between checks to the bean&#8217;s source code, if it has changed, the bean will be refreshed.</p>
<p>Another thing to mention would be that new changes are effective only on the bean&#8217;s next usage. For example if you make five changes to the beans source code, but never make a call to the bean between changes, it will only be reloaded once, when you actually make a call to the bean. </p>
<p>Also, refreshable beans behavior does not apply to dynamic language source code defined inline, inside the context file, it only applies to beans where changes to source code file can be detected, for example if it&#8217;s stored on the filesystem.</p>
<p>That&#8217;s about it. You can find more on springsource&#8217;s website: <a href="http://static.springsource.org/spring/docs/2.5.x/reference/dynamic-language.html">Dynamic language</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2010/01/springs-refreshable-beans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Musings of a SpringOne 2009 Attendee &#8211; Day 3</title>
		<link>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-3/</link>
		<comments>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-3/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 02:20:05 +0000</pubDate>
		<dc:creator>Sudhakar Ramasamy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Conference]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=187</guid>
		<description><![CDATA[Agile Architecture &#8211; Technologies and Patterns &#8211; Kirk Knoernschild
Some of the questions this session set out to attempt to answer were

What is architecture?
What defines architecture?
What are architectural decisions?
Is architecture a forward only decision?

 Several definitions of Architecture were quoted from prior literature. Such as architecture being the the shared understanding of the system being built. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15662"><strong>Agile Architecture &#8211; Technologies and Patterns &#8211; Kirk Knoernschild</strong></a></p>
<p>Some of the questions this session set out to attempt to answer were</p>
<ol>
<li>What is architecture?</li>
<li>What defines architecture?</li>
<li>What are architectural decisions?</li>
<li>Is architecture a forward only decision?</li>
</ol>
<p><em> </em>Several definitions of Architecture were quoted from prior literature. Such as architecture being the the shared understanding of the system being built. Shared understanding between a group of people who need to communicate about it &#8212; developers and architects, or technical and management etc.<br />
Lean principles are you delay <span id="more-187"></span>the decision till it is required and till after you have enough information to make an effective decision. Does this mean you should not make decisions based on incomplete information? I disagree on the &#8220;effective decision&#8221;. How do you even know what is effective decision? Something that is effective today more than likely will not be effective tomorrow. The world we live in is a naturally changing world. You delay the decision till the last responsible minute. But when you have to make the decision you do it based on the best available information at that point.<br />
The goals of architecture were then discused. I thought this was a very insigtful analysis. We were first shown how the impact of change and the cost of change influence architecture and design. Hgh impact and high cost of change require architecture and design. If the change has high impact, but low cost then architecture may not be as important as long as you have measures to mitigate the change such as unit and functional tests. Or if the change has low impact but high cost, if you are prepared to absorb the cost, then architecture may not be as important either though this is more unlikely. The end goal of architecture is to reduce the impact and cost of change.<br />
Are flexibility and complexity opposing goals? Higher flexibilty introduces higher complexity. It goes back to choosing your battles. If the impact of change is not significant then it doesn&#8217;t have to be flexible and thus not complex. So the question is which parts of the system needs to be flexible.<br />
The <a href="http://c2.com/cgi/wiki?ReuseReleaseEquivalencePrinciple">release-reuse equivalence principle</a> is that the unit of release is the unit of resue. We see this in daily practice. And consequently reuse fits nicely into modularity. In other words, what is modular can be released as a unit and reused.<br />
So then what correlations can be made between agility and modularity?</p>
<ul>
<li> Structural flexibility which defines modularity</li>
<li> Temporality or the ability of the system to accommodate future change which defines agility</li>
</ul>
<p>(This stuff is good I&#8217;m thinking!)</p>
<p>A jar file</p>
<ul>
<li> unit of resuse</li>
<li> unit of composition</li>
<li> unit of deployment</li>
<li> unit of management</li>
</ul>
<p>So why not make jar files first class citizens on the java platform? Why do we have to package a jar inside a WAR or a EAR? Why are we flattening these modular units.<br />
Increasing a system&#8217;s modularity leads to easier to maintain and extendable software. In a non-modular system, being afraid to make changes to the code base causes us to do things such a copy/paste, or write duplicate code which further degrades the codebase. Guilty as charged!<br />
Modularity helps in assessing the impact and cost of change. When we know what other modules depend on the module that needs to be changed, we have a more clearer understanding of the risks, impacts and cost of that change. I wonder if the roadblock to modularity is our platforms.  What if the WAS and Glassfish and Weblogics of the world allowed us to deploy our applications as sets of OSGi bundles?</p>
<p>There was a comment about how WAS 7 has made giant strides towards being modular internally by adopting OSGi under the hood. Apparently it starts under 5 seconds for a non-ejb application. I had to recently run WAS 7 in development mode inside my RAD workspace. And I can vouch for the fact that startup time was certainly several magnitudes more than 5 secs. Maybe I&#8217;m missing something here.<br />
So what are benefits realized in the runtime because of modularity?</p>
<ol>
<li> Dynamic deployment</li>
<li> Multiple versions</li>
<li> Enforce dependencies</li>
</ol>
<p>&#8230;.and all at runtime.<br />
Modular tension is higher ease of use of an artifact makes it more difficult to reuse. Higher ability for reuse (i.e. finer grained artifacts) makes it more difficult to use. Are reuse and use always inversely related?</p>
<p>A few thoughts around this:</p>
<ol>
<li> Public methods shouldn&#8217;t necessarily be published methods. Currently this is enforced via Javadocs unless you are using OSGi</li>
<li> Interfaces should be close to their usage and not close to the implementations. This makes sense for framework APIs. It probably applies to business applications as well. What&#8217;s good for the  goose is  good for the gander.</li>
<li> Separate the interface from the implementations not just at the package level but also as deployment artifacts. You see this in framework apis now (javaee-api.jar is separate from its implementation jar). But not so much in business applications. If we did, it would aid in providing more predictable API evolution. We would be able to fix a defect or enhance an internal function in the implementation and then release just the newer version of the implementation built against the same old version of the API. The consumers of this API would not see any suprises since the API itself hasn&#8217;t changed. Instead when we package both the interface and implmentation as a single artifact, it is more difficult to avoid suprising the consumers of the API.</li>
<li> Exceptions should be close to where they are thrown. So they should be part of the API.</li>
</ol>
<p>So is OSGi the holy grail of runtime modularity?<br />
Yes and no. It forces runtime modularity but we are still required to design our apps modularily. A sample application (kcode.googlecode.com) that echoed these principles was demoed. Another tool that was mentioned was JarAnalyzer which gives us a visual image of our jar dependencies by analyzing the project. It can be included in the build script. The tool was built by the author.<br />
Overall I really liked this session because of how it tied all the buzz and technical mumbo-jumbo around modularity and OSGi into business speak, something you can pitch to management.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15653">That old Spring magic has me in its SpEL: DI Wizardy with the Spring Expression Language &#8211; Craig Walls</a></strong></p>
<p>Spring Expression Language or SpEL is probably the most prevasive feature in Spring 3.0. From what I&#8217;ve seen so far it can be used in DI, in Spring Web Flow, in Spring Security, Spring Integration. So if you are looking at taking advantage of Spring 3.0 you should probably look at SpEL. A SpEL expression is provided within a #{ } similar to the JSF EL. The source code (http://spring.habuma.com/examples/SpEL-examples.zip) contains well documented examples of the different forms of SpEL expressions. Here is a sampling:</p>
<p>Instead of having to use environmentPlaceHolderConfigurer you could do:</p>
<p>#{systemProperties['region']}<br />
#{systemEnvironment.region}</p>
<p>You can refer to the following:<br />
#{bean.property}<br />
#{request.getParamenter(&#8221;action)}<br />
#{request.getAttribute(action&#8221;)}<br />
You can inject these directly into bean properties instead of having to do it in code. Very cool! This is just scratching the surface. Go now and checkout the source. There are some amazing things you can do with collections similar to what you can do with the Bean predicate except more succintly. SpEL can be used as a configuration tool (both in applicationContext.xml as well as with Spring annotations) as well as a general purpose parser a la apache commons beanutils via the SpELAntlrExpressionParser.</p>
<p>SpEL is nice but there is no type safety or syntax checking. It seems to impart a funtional flavor when used with collections.<br />
Craig had one test class with individual test methods that showcased each of the capabilities of SpEL. He would make a change in the test method and hit save and the test would be automatically run giving him immediate feedback on pass or fail. He was using <a href="http://infinitest.org/web/guest/home">Infinitest</a> who are handing out free licenses for individual developers. It uses JUnit. I hope they also provide TestNG support.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15643">Working with Spring Web Flow &#8211; Keith Donald</a></strong></p>
<p>I was convinced to attend this session after the Spring Faces session. Spring Web Flow is a stateful web conversation framework. The flow persistence strategy is pluggable. By default it uses Session but it doesn&#8217;t necessarily have to be session. Useful in a multi-step progression type user interaction as well as in single page AJAXy interactions.<br />
Keith showed how pages are bookmarkable and how the browser Back button works as it  should. Web flow uses an encrypted key in the URL parameter for the key. Example e5s1 where the 5 indicates the execution of time of this execution and the 1 indicates the snapshot or step in the flow. You can modify the key in the URL and the URL is still addressable.<br />
The execution has a lifecycle and upon completion it is garbage collected which means it is no longer active. It does automatic session cleanup after the flow ends. Spring Web Flow can replace t:saveState and all the extra coding that goes with it to maintain state particularily in multi-page flows.<br />
There was a question about where we can introspect the flow execution repository for use cases such as bread crumbs navigation. Apparently you can but it is still very involved and this is being addressed in the next version. Keith demonstrated the hotel web application sample from Spring and the flow for the booking scaenario. External flow definition modules are compiled and refreshed upon changing without app server restarts. Code completion is available in the editor (STS?)</p>
<p>Can use evaluate to execute some method and assign to a scoped varaible. SpEL can be used in Web Flow. The model attribute on view-state is used to bind form parameters to bean properties. I didn&#8217;t quite catch the validation part of it.</p>
<p>I definitely need to take a good look at Spring Web Flow and it&#8217;s integration with JSF.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15654">Spring Integration 2.0 Preview &#8211; Mark Fisher</a></strong></p>
<p>Spring integration provides an embedded message bus that lives within an applicationContext with all components being Spring managed objects. Many of the patterns from the Enterprise Integration Patterns books are implemented. A message wraps around a payload (XML/java Object) along with headers. A Message Channel is the communication link between producers and consumers and provides loose coupling.</p>
<p>This is another one of those core technologies that I think can underpin the architecture of a flexible enterprise application.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15651">Case Study: SRM 2.0 &#8211; A next generation shared resource management system built on SpringSource dm Server &#8211; Matt Stine</a></strong><br />
This session was about how St. Jude Children&#8217;s Research Hospital rebuilt their Shared Resource Management System as a modular application to be extensible to meet growing business needs. The business need was to track samples as they progressed through the different stages in a laboratory. There are several labroatories and each usually has it&#8217;s own set of unique requirements.<br />
The previous system consisted of:</p>
<ol>
<li> Core domain model</li>
<li> Core services platform</li>
<li> Web platform</li>
<li> Laboratory specific extensions
<ol>
<li> DB Schema &#8211; extendable by hanging tables of existing tables</li>
<li> Domain model</li>
<li> Services</li>
</ol>
</li>
</ol>
<p>Overall the shema had 200 tables that was becoming unmanageable. And they had to follow a monolithic deployment model. When it was decided that they need to rethink the application it was based around extensiblity</p>
<ol>
<li>primarily by configuration</li>
<li> feature modularity</li>
</ol>
<p>An <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model">EAV data model</a> was chosen for it&#8217;s extensibility. The system was built around some core concepts such as a kernel and business activity source. Using OSGi as the underlying  platform, they were able to introduce new technologies behind an OSGi service without running risks of breaking other parts of the application. From a development perspective OSGi lets them ship the interface out to a 3rd party team and have them implement it.</p>
<p>Used 3 to 4 days of consulting work from SpringSource the team was able to ramp up on OSGi, Spring dm server and STS starting in January &#8216;09. They then spent the first 3 to 4 months working out the kinks since the tools were still in their 1.0.0 version. In their experience, adopting OSGi led to a short time fall-of in productivity as they ramped up on the technology but they are now reaping the long term benefits of modularity. Their reporting solution was implemented against a real time data mart that is relational and using messaging via Spring Integration and a databus architecture.</p>
<p>It was pretty awesome to see that they had developed a modular enterprise application based on OSGi leveraging Spring Integration. After the presentation I got the chance to talk to the technical lead on this project from St. Jude. He told me how respecting the small set of simple tenets of good application design enforced by OSGi, depending on interfaces, and use of shared bundles was really the reason for their success. OSGi is not complex and there is no need to make it complex. Wise words.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Musings of a SpringOne 2009 Attendee – Day 2</title>
		<link>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-%e2%80%93-day-2/</link>
		<comments>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-%e2%80%93-day-2/#comments</comments>
		<pubDate>Thu, 22 Oct 2009 02:12:54 +0000</pubDate>
		<dc:creator>Sudhakar Ramasamy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Conference]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[sud]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=129</guid>
		<description><![CDATA[Running a day late on my posts. Here&#8217;s day two (yesterday)
Grails Quick Start &#8211; David Klien
David walked through the creation of a Grails web application to track a JUG&#8217;s meeting schedule. I liked his presentation style or maybe because the room wasn&#8217;t very crowded things just registered better. Picked up a few tips such as [...]]]></description>
			<content:encoded><![CDATA[<p>Running a day late on my posts. Here&#8217;s day two (yesterday)</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=16412">Grails Quick Start &#8211; David Klien</a></strong></p>
<p>David walked through the creation of a Grails web application to track a JUG&#8217;s meeting schedule. I liked his presentation style or maybe because the room wasn&#8217;t very crowded things just registered better. Picked up a few tips such as the Bootstrap class. Grails still has a ways to go in the eclipse tooling. It would&#8217;ve been nice to have been able to File &#8211;&gt; New Project and follow along. Too bad <a href="http://www.jetbrains.com/idea/nextversion/editions_comparison_matrix.html">IntelliJIDEA CE</a> doesn&#8217;t support grails though there has been plenty of buzz on the latest <a href="http://www.springsource.com/products/sts">STS</a>. Downloading this right now. Only 3 more hours for the download to complete!</p>
<p>I think I&#8217;m beginning to dig duck typing. All in all the presentation encouraged me to put my head down and hammer out a sample app to start building some grails knowledge. More homework!<span id="more-129"></span></p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=16414">XML and Web Services with Groovy &#8211; Paul King</a></strong></p>
<p>XMLParser and XMLSlurper were covered. I&#8217;d attended a similar talk by Scott Davis at NFJS. So I wasn&#8217;t all oo-ahh about it. But I did pick up on a few things. Like the XMLSlurper&#8217;s lazy evaluation. Apparently lazy evaluation is more pervasive in Groovy and you see it in sql resultset processing as well. This actually makes groovy faster than Java in these use cases. We also saw how existing Java XML libraries such as DOM4J can be used within groovy.</p>
<p>For the web service half GroovyWS was shown. In literally three lines of code you can standup a POJO/POGO as a web service endpoint. Not likely to be used in production but this shows how you can easily take an existing Spring bean and expose it&#8217;s responsibilities as a web service for a proof of concept. A simple SOAP webservice consumer was shown in 4 lines too. Also learnt that Synapse and ServiceMix have groovy support built into them.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15640">Simplifying Java Server Faces Development with Spring Faces &#8211; Jeremy Grelle</a></strong></p>
<p>I probably got most out of this presentation. At times I felt like Jeremy was speaking directly to me. My day job involves JSF 1.2 and Jeremy was pointing out all the (anti) patterns we employ in order to overcome the limitations of JSF 1.2.</p>
<p>He pointed out two ways to integrate JSF with Spring</p>
<ol>
<li>JSF centric &#8211; where Spring simply replaces the managed bean functionality of JSF. With the caveat that if you need to dynamically inject a Spring bean it is not possible using Spring 2.5. In those situations you&#8217;ll need to revert to JSF managed beans. You could still use the JSF managed beans for view action classes and inject Spring service beans into the action classes. The JSF centric approach is the one I&#8217;m familiar with.</li>
<li>The Spring centric on the other hand does all of the following:
<ol>
<li> JSF plugs into Spring as the View layer</li>
<li> Does not use the FacesServlet</li>
<li> Spring MVC + Web Flow together replace the</li>
</ol>
<ul>
<li> managed bean provider</li>
<li> request dispatcher</li>
<li> navigation handler</li>
<li> state manager</li>
</ul>
</li>
</ol>
<p>Spring Web Flow provides the conversation scope (more than Request but less than Session scope) that is sorely missing in JSF.</p>
<p>In the Spring centric approach one would use the Spring MVC DispatcherServlet for Controllers for stateless intrerations (basically selecting JSF views for rendering) and Spring Web Flow for stateful interactions.</p>
<p>He demoed what I think was JSF 2.0 Custom components. And how one can wrap them with Spring Faces components to do client side validation etc. The Spring Faces components wrap Dojo under the hood and this same technique can be used by us to wrap other Dojo components that are not already available in Spring Faces.</p>
<p>Another issue we run into frequently in JSF 1.2 is being able to initialize a view. The framework does not provide a built-in way to do this. Spring Web Flow has a clean way to do this using on-Render in the flow definition. Web flow also has viewScope allowing you to do multiple interactions with the same page without having to go back to the database.</p>
<p>The big benefit of Spring Faces is it&#8217;s integration with Web Flow. And Web Flow makes the restarts due to changes in faces config a thing of the past.</p>
<p>There was a slide that compared the pet clinic application built using Spring Faces and pure JSF. The Spring Faces application used 1/3rd the lines of code &#8212; which was believable considering how the faces config was completely trimmed and how a lot of the workaround code was eliminated. Some of the new features requires JSF 2.0.</p>
<p>What about Seam? Not sure if and how Seam would work in a Spring web stack.</p>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=16448">Grails Security &#8211; Ken Sipe</a></strong></p>
<p>This session covered SQL injection attacks and XSS attacks. Made me wonder how many of us building applications that live behind the firewall really code for this. Ken also showed examples of how an enterprising hacker can discover the data structure of your application using SQL injection. O/R frameworks solve most of the SQL injection problems but apparently there are edge cases where these frameworks still spit out un-parameterized queries and how we need to always verify the SQL being generated. Another question about input validation and what is it that you are validating. This is still a hazy area and there was no definitive answer on this. Also Stories and Abuse Stories &#8212; are we writing code that prevents the user from breaking (nicer word for hacking?) the application? Does this need to be part of the story acceptance criteria.</p>
<p>We then got to look at security in Grails and how we need to add the html codec in the Config.groovy to escape out the HTML.</p>
<p><em>grails.views.default.codec = &#8220;html&#8221;</em> in <em>/conf/Config.groovy</em>.</p>
<p>Ken mentioned the <a href="http://www.intelligrape.com/blog/?p=49">Command Object</a> and treating the interaction with the data store as different from the interaction with the web. We then looked at Cross Field validation in Groovy which was pretty sweet.</p>
<p>It was mentioned that we should never show error pages to users which to me makes absolute sense in a public facing web application. But are there internal applications that we may need to expose the error message to the end user &#8212; such as when we cannot duplicate the issue in the  support or development environments and it is a fairly complex interaction that is quicker to have the user send you the stack trace or walk you through the steps to reproduce the issue. We are trading security for ease of troubleshooting. How big a risk is this in internal apps?</p>
<p>Ken said something interesting about handling <a href="http://palisade.plynt.com/issues/2006Aug/session-riding/">session riding attacks</a> &#8212; upon login expire the newly authenticated session and create a new one based on the expired session. For requests that are highly sensitive, using encrypted tokens with a timeout. So if the following request doesn&#8217;t provide the token and doesn&#8217;t meet the time expectation then you can invalidate it.</p>
<p>Few resources that were mentioned:</p>
<ol>
<li> Spring security for Grails (SecurityConfig.groovy)</li>
<li> <a href="http://cwiki.apache.org/confluence/display/SHIRO/Index;jsessionid=1C1152DB0161A823BE61ACB60A1C8780">Apache Shiro</a></li>
<li> <a href="keylength.org">keylength.org</a></li>
<li> <a href="http://www.amazon.com/Writing-Secure-Second-Michael-Howard/dp/0735617228">Writing Secure Code</a> &#8211; best book on security as per Ken (believe it or not from Microsoft press)</li>
<li> <a href="http://www.owasp.org/index.php/Category:OWASP_WebGoat_Project">Webgoat</a> &#8211; learning tool to learn about securing Java EE applications. This looks like something I need to check out. More homework again!</li>
<li> <a href="http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API">EASPI</a> from owasp attempts to solve the security concern at the framework level.</li>
</ol>
<p><strong><a href="http://www.springone2gx.com/conference/new_orleans/2009/10/session?id=15636">Case Study: RESTful Web Services at Orbitz &#8211; Alex Antonov</a></strong></p>
<p>Alex talked about solving the problem of management of shared, versioned dependencies with serializable objects in a highly distributed environment. And the pain involved in keeping about 60 to 70 systems in sync during upgrades.</p>
<p>The original maze of systems were implemented in JINI. But since Sun is no longer behind JINI and JINI is no longer evolving they have had to ditch it. They actually won an award for their use of JINI. But they have migrated to a REST based architecture using Google Protocol Buffers for the messages across the wire instead of XML or JSON. I should  have paid attention during Octavian&#8217;s protocol buffers presentation! So protocol buffers is a substitution for java serialization. It is 7 to 10 times faster than JSON and even faster than JINI/JERI.</p>
<p>Protocol buffers provides transparent versioning where if a message needs to flow through System A &#8211;&gt; System B &#8211;&gt; System C, you can upgrade the message structure (upto a certain extent) in System A and  System C and not have to modify System B. Protocol buffers lets connected systems mesh both backwards and forwards at the joints without the developer having to put in any effort.</p>
<p>We were then introduced to REST API best practices. Didn&#8217;t see much new stuff that I hadn&#8217;t seen before. Speaks for REST which is supposed to be simple with a few guiding principles. One thing I did learn about writing REST APIs was to use query strings for optional filtering. Another was to let the client define what message format they will accept via the Accept header. You can then use plugins for protocol buffers to send down the message in the requested format.</p>
<p><strong>TECHNICAL KEYNOTE &#8211; Adrian Colyer</strong></p>
<p>Adrian Coyler&#8217;s keynote started of very entertaining when he walked acros the stage with just the handle of his new roll-on bag. Story about how his luggage got ripped out and disappeared on his way to SpringOne. We heard about some of the new things in Spring. But he moved quickly to showing SpringSource&#8217;s last acquisition, <a href="http://www.cloudfoundry.com/">Crowd Foundry</a> and it&#8217;s capabilities. Having seen Google&#8217;s App Engine before I wasn&#8217;t very impressed. Essentially Crowd Foundry provides a developer centric way to deploy Java applications on Amazon EC2 including a plugin for Eclipse (or does this require STS?).</p>
<p>VMware then took over explaining their technology blueprint that leverages Spring tc server running in virtualized environments. Looks like VMware which has till date been visibile mostly in the infrastructure and operations space will soon be surfacing virualization and the cloud to developers. Some of the technologies that were showcased were:</p>
<ol>
<li> <a href="http://www.vmware.com/products/vmotion/">vMotion</a></li>
<li> <a href="http://www.vmware.com/products/drs/">Dynamic Resource Scheduling</a></li>
</ol>
<p>Interesting stuff. I later on learnt that on of the organizations that was implementing an enterprise OSGi application was using vMotion at the infrastructure layer for fail over.</p>
<p><strong>Spring Core BOF</strong></p>
<p>Spring ESB? More like Environment Specific Beans may be coming in a future release of Spring 3.x.This should eliminate the need to use environment placeholder configurers for environment specific beans. Learnt that spring-oxm can be used outside of the spring-ws.</p>
<p>http://www.springbyexample.com was suggested as a useful resource for learning.</p>
<p><strong>Wrap up</strong></p>
<p><a href="www.manning.com/">Manning</a> was running a treasure hunt of sorts all through the conference with free book vouchers hidden around the conference areas. I had absolutely no luck!</p>
<p>One of the best parts of this SpringOne conference is rubbing shoulders with guys who&#8217;ve written the books, written the code, and give talks about the technologies that we use. These guys literally sit around with the attendees and are there to geek out with us regular joes. I got the chance to meet Craig Walls and talk about OSGi and Venkat and pick his brain on functional languages. And of course there is the always helpful SpringSource team easily recognized by their &#8220;uniforms&#8221;.</p>
<p>Looking forward to more. Also got my first <a href="http://twitter.com/sudr">re-tweet</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-%e2%80%93-day-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Musings of a SpringOne 2009 Attendee &#8211; Day 1</title>
		<link>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-1/</link>
		<comments>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-1/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 13:39:35 +0000</pubDate>
		<dc:creator>Sudhakar Ramasamy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Conference]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[sud]]></category>

		<guid isPermaLink="false">http://blogs.sourceallies.com/?p=125</guid>
		<description><![CDATA[It has finally arrived. SpringOne which I have been anticipating for over a month is finally here and it  couldn&#8217;t have come sooner. I need one more blast of warm sunny weather before the hibernation months of winter. My day started at 3:30 am, well actually 4:00 am as I managed to roll out of [...]]]></description>
			<content:encoded><![CDATA[<p>It has finally arrived. SpringOne which I have been anticipating for over a month is finally here and it  couldn&#8217;t have come sooner. I need one more blast of warm sunny weather before the hibernation months of winter. My day started at 3:30 am, well actually 4:00 am as I managed to roll out of bed. But before long I was sitting on the plane to St. Louis going over the conference schedule doing my first round of eliminations. This is the easy one. I knock out all the sessions that I have absolutely no interest in going. The ones that even the temptation of free beer cannot get me to go to. You get the idea. Even with an 8 track schedule there wasn&#8217;t a lot I could eliminate. But I had started the process. Once in St. Louis I had a 4 hour stop-over.<span id="more-125"></span></p>
<p>This is my first trip through St. Louis and I kept thinking that I need to visit this place. It&#8217;s only 40 mins flying time from Des Moines. So it can&#8217;t be a very long drive. A quick tour of the airport and a quick survey of the eateries led me to the Wolfgang Puck Express restaurant. A big &#8216;ole breakfast sandwich and coffee later I was back on the schedule working my way through the second round of eliminations. The session descriptions on the conference schedule are usually indicative of the content. But sometimes you never know. Fortunately I&#8217;d been to NFJS couple months earlier. So that helped me eliminate some of the similar talks and sometimes the same talk from NFJS. I knew I still had at least three or four rounds before I could narrow my schedule down. A lot of the sessions sound very interesting and it&#8217;s going to be difficult to choose between them but it has to be done and I decided to go over it again on my way to New Orleans. For now I&#8217;m going to work on a OSGi blog posting.</p>
<p>St. Louis to New Orleans is a little under 2 hours flying time. Enough time to read the in-flight magazine cover to cover&#8230;ok I skipped the inflight entertainment section. I went down the conference schedule one more time to weed out the &#8220;not useful to me right now&#8221; sessions. I&#8217;ve found that while hands-on practical sessions are great, if you do not have immediate applications for them you don&#8217;t derive their full benefit. Instead I&#8217;m trying to assemble a mix of immediately applicable hands-on sessions, sessions that build upon my existing skills, overview type sessions and sessions which I think may have some potential near future applications. I still ended with some time-slots where as many as 5 of the 8 sessions made it to my 3 round. So yeah still plenty of work to do. I&#8217;m sure we&#8217;ll be getting the slides to all the sessions. I wonder if we will get the videos though.</p>
<p>So New Orleans is my new favorite airport to transit through. Guess why!? Free wireless internet baby! It&#8217;s not the world&#8217;s fastest but it&#8217;s free. In all the major US airports I&#8217;ve transited through not one has had free wireless..not O&#8217;Hare, not JFK, not LAX. Somebody should start a website tracking airports with free wireless. It may influence a lot of travel plans <img src='http://blogs.sourceallies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Met up with Matt at the New Orleans airport and took a cab ride to our hotel in downtown. On the way I was reminded a couple times about big city driving. After check-in we headed out to the conference hotel which, the newly reopened Roosevelt which is right across the street from the hotel we are staying in. Thanks to Mandy for booking us into our very convenient hotel. I won&#8217;t have an excuse to miss the morning sessions <img src='http://blogs.sourceallies.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . I was a little surprised to see a handful of vendor stalls. We got to talk to the VMware guys about Spring and VMware and from the sounds of it looks like they are trying to sell a cloud provider solution for those who want to get into business of providing cloud service solutions a la google, amazon etc. Apparently this will give the consumer the benefit of switching between different providers as opposed to currently being locked-in. Also got the chance to talk to the BIRT guys and catch up how BIRT has matured over the last couple years since I used it. I&#8217;d be interested to hear if anyone else has any experience using BIRT over JasperReports or other open-source reporting solutions. Dinner was pretty awesome &#8212; New Orleans cuisine for the most part including my first taste of bread pudding&#8230;yumm.</p>
<p>Rod Johnson&#8217;s keynote followed. He covered what Spring 3.0 was about and some of the new stuff, pointing out sessions that would follow during the next two days. There was a demo on Spring &#8211; Flex Blaze DS integration. It looked pretty cool though a lot went over my head. I think it was building on top of Spring JMS. The big announcement was the Spring tc Developer server which gives the developer a pretty powerful tool to look into the guts of an application. The demo showed where you can make a request on slow loading page and you then drill down through the Insight tool to the specific slow running query. Just scraping what was demoed. Apparently the first release is not due until later this year. I&#8217;ll probably pull down the Milestone and take a more closer look at this.</p>
<p>Time to go to bed and rest up. Day 2 will be another long day. But before that I need to pick out at least the first two sessions for the day. The conference slides were distributed on thumb drives. So I did a quick scan and was able to pick out a couple sessions before calling it a night.</p>
]]></content:encoded>
			<wfw:commentRss>http://blogs.sourceallies.com/2009/10/musings-of-a-springone-2009-attendee-day-1/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

