<?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>Technophile Blog</title>
	<atom:link href="http://gordondickens.com/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>http://gordondickens.com/wordpress</link>
	<description>Random geek topics on open source Java technologies</description>
	<lastBuildDate>Mon, 01 Apr 2013 17:49:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Sawing through the Java Loggers</title>
		<link>http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/</link>
		<comments>http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/#comments</comments>
		<pubDate>Thu, 28 Mar 2013 02:09:07 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Jakarta Commons Logging]]></category>
		<category><![CDATA[Java Util Logging]]></category>
		<category><![CDATA[LogBack]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[SLF4J]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[Log4J]]></category>
		<category><![CDATA[Logback]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=304</guid>
		<description><![CDATA[Sawing through the Java Loggers I know what your thinking, &#8220;It&#8217;s just logging!&#8221;. This small, yet common part of our applications, provides developers, QA and troubleshooters with information to help in determining code execution sequences, inspecting data values and trouble &#8230; <a href="http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h2>Sawing through the Java Loggers</h2>
<p><a href="http://gordondickens.com/wordpress/wp-content/uploads/2010/10/Its-Log.jpg"><img style="float:left;margin:5px;" title="It's Log" src="http://gordondickens.com/wordpress/wp-content/uploads/2010/10/Its-Log.jpg" alt="It's Log!" width="125" height="101" /></a></p>
<p>I know what your thinking, &#8220;It&#8217;s just logging!&#8221;. This small, yet common part of our applications, provides developers, QA and troubleshooters with information to help in determining code execution sequences, inspecting data values and trouble spots within our applications.  The reality is that without robust logging implementations we would lose a significant troubleshooting tool.</p>
<p style="text-decoration:underline;font-weight:bold">Java Logging Choices</p>
<ol>
<li>System.out/System.err</li>
<li>java.util.logging (JUL)</li>
<li>Apache commons jogging (aka Jakarta Commons Logging &#8211; JCL)</li>
<li>Log4j</li>
<li>SLF4j</li>
<li>Logback</li>
</ol>
<p><br/></p>
<h2 style="border-width:1px;border-style:solid;color:darkblue;padding:5px;">System.out &amp; System.err</h2>
<p>In the early days (hopefully not now) we used to use the old <code>System.out.println()</code> method of logging.  We would quickly discover using them is NOT good.</p>
<p style="text-decoration:underline;font-weight:bold">Reasons to avoid <code>System</code> methods</p>
<ul>
<li>We can not disable in production, affecting performance and potentially compromising data security.  Oh we do have <code>System.err.println()</code> but still not good enough</li>
<li>We can not configure how much or little information is reported (logging levels)</li>
<li>In a clustered environment, we can not configure a central location for information</li>
<li>System.out performs poorly&#8230; see <a href="http://jorgecardoso.org/blog/index.php?/archives/116-java.util.logging-versus-System.out-performance.html">Logging vs System.out Performance</a></li>
<li>Metadata is unavailable and must be coded for each System.out, which is inevitably not going to be done or very inconsistent at the least</li>
</ul>
<p style="font-weight:bold">*** DO NOT USE <code>System.out</code> or <code>System.err</code> anywhere, ever! ***</p>
<p><br/></p>
<h2 style="border-width:1px;border-style:solid;color:darkblue;padding:5px;">java.util.logging (JUL)</h2>
<p>Java provides a logging option which is a step forward in logging.  However, it is not widely used as it came late to the party.  Not many open source frameworks use JUL.  Typically you will find this in <code>com.sun</code> or <code>com.oracle</code> projects such as Jersey.</p>
<p><br/></p>
<h2 style="border-width:1px;border-style:solid;color:darkblue;padding:5px;">Log4j</h2>
<p>Log4j is an Apache project that has been around for some time and is widely used by open source projects.  Log4j provides a flexible logging framework but is a bit dated at this point.</p>
<p><br/></p>
<h2 style="border-width:1px;border-style:solid;color:darkblue;padding:5px;">SLF4j &#8211; Logging API</h2>
<p>We have many options for logging, and with our open source projects we typically include projects that might implement JCL and JUL.</p>
<p>SLF4j (<em>Simple Logging Facade for Java</em>) provides a common logging interface for our projects.  Most respectable open source projects now use SLF4j for the configurability and flexibility to change logging implementation.  Think of SLF4j as the common interface (API) for our logging implementation choice.</p>
<p>All of our logging code should use the same SLF4j API.  For example:</p>
<pre class="brush:java" style="font-size:75%">
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
…

public class MyClass {
  private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
…
 
  public void someMethod() {
    logger.debug("something is happening");
  }

}
</pre>
<p style="text-decoration:underline;font-weight:bold">Basic SLF4j Maven Dependencies</p>
<pre class="brush:xml" style="font-size:75%">
&lt;properties&gt;
  &lt;slf4j.version&gt;1.7.5&lt;/slf4j.version&gt;
  &lt;logback.version&gt;1.0.11&lt;/logback.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;
  &lt;!-- SLF4J - logging api --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;!-- Logback - logging impl --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;
</pre>
<p style="text-decoration:underline;font-weight:bold">Advanced SLF4j Maven Dependencies</p>
<pre class="brush:xml" style="font-size:75%">
&lt;properties&gt;
  &lt;slf4j.version&gt;1.7.5&lt;/slf4j.version&gt;
  &lt;logback.version&gt;1.0.11&lt;/logback.version&gt;
&lt;/properties&gt;

&lt;dependencies&gt;
  &lt;!-- SLF4J - logging api --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;!--  Interceptor for Commons-logging --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;!--  Interceptor for java.util.logging --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;

  &lt;!-- Logback - logging impl --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-core&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
&lt;/dependencies&gt;
</pre>
<p style="text-decoration:underline;font-weight:bold">SLF4j Advantages</p>
<ul>
<li>One logging strategy for all</li>
<li>String placeholders
<ul>
<li>logger.debug(&#8220;The value of {} is {}&#8221;, myVar, myValue);</li>
</ul>
</li>
<li>Intercepts <code>commons-logging</code>
<ul>
<li>Include <code>jcl-over-slf4j</code> dependency</li>
<li>Should exclude <code>commons-logging</code> dependencies from project</li>
</ul>
</li>
<li>Can intercept <code>java.util.logging</code>
<ul>
<li>Include <code>jul-to-slf4j</code> dependency</li>
<li>Requires registration of classes within the application</li>
<li>See: <a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/#logging">Enterprise Spring Best Practices Blog</a></li>
</ul>
</li>
<li>Can intercept <code>System.out</code> &amp; <code>System.err</code>
<ul>
<li>Requires including dependencies</li>
<li>Requires registration of classes within the application</li>
<li>See: <a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/#logging">Enterprise Spring Best Practices Blog</a></li>
</ul>
</li>
</ul>
<p><br/></p>
<h2 style="border-width:1px;border-style:solid;color:darkblue;padding:5px;">Logback &#8211; Smarter Logging</h2>
<p>Logback is a project from the creator of Log4j and SLF4j, Ceki G&#252;lc&#252; (<em>pronounced Jacky Guldju</em>).</p>
<p>The first article to read is: <a href="http://logback.qos.ch/reasonsToSwitch.html">Logback: Reasons to Switch</a></p>
<p><em>Simple logback.xml File</em></p>
<pre class="brush:xml" style="font-size:75%">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration debug="true" scan="true" scanPeriod="30 seconds"&gt;

  &lt;appender name="console" class="ch.qos.logback.core.ConsoleAppender"&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;%-5level %logger{0} - %msg%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;logger name="com.gordondickens.demo" level="debug" /&gt;
  &lt;logger name="org.springframework.beans" level="trace" /&gt;

  &lt;root level="warn"&gt;
    &lt;appender-ref ref="console" /&gt;
  &lt;/root&gt;
&lt;/configuration&gt;
</pre>
<p style="text-decoration:underline;font-weight:bold">File Appenders</p>
<p>In addition to the console appender, there are File and RollingFile.  The Rolling file appender allows <em>time-based</em> and <em>size-based</em> options, with the ability to specify how many files to keep and optional compression (zip).<br />
See: <a href="http://logback.qos.ch/manual/appenders.html">Logback Appenders</a></p>
<p style="text-decoration:underline;font-weight:bold">Speaks Native SLF4j</p>
<p>We saw above that simply replacing Log4j with Logback, we now have logging through SLF4j. Actually, its one dependency less, as we no longer would include the <code>slf4j-log4j12</code> dependency.</p>
<p style="text-decoration:underline;font-weight:bold">RESTful &amp; Web Access Logging</p>
<p>We can use logback-access to provide server access logging.  This can prove to be very helpful when troubleshooting RESTful web services as well as for web applications.  In our application&#8217;s <code>src/main/resources</code> directory create the file <code>logback-access.xml</code>. </p>
<p><em>logback-access.xml</em></p>
<pre class="brush:xml" style="font-size:75%">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration&gt;
  &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /&gt;

  &lt;appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"&gt;
    &lt;file&gt;${user.dir}/logs/app-access.log&lt;/file&gt;
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"&gt;
      &lt;fileNamePattern&gt;${user.dir}/logs/app-access.%d{yyyy-MM-dd}.log.zip&lt;/fileNamePattern&gt;
    &lt;/rollingPolicy&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;combined&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;
  &lt;appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;%n%n%fullRequest%n%n%fullResponse%n%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;appender-ref ref="FILE" /&gt;
  &lt;appender-ref ref="STDOUT" /&gt;
&lt;/configuration&gt;
</pre>
<p><em>web.xml</em></p>
<p>The &#8220;TeeFilter&#8221; handles the access logging. See <a href="http://logback.qos.ch/access.html">http://logback.qos.ch/access.html</a><br />
The optional &#8220;ViewStatusMessagesServlet&#8221; allows us to browse the log back configuration via the url <code>/logbackstatus</code>.  See <a href="http://logback.qos.ch/manual/configuration.html ">http://logback.qos.ch/manual/configuration.html</a> </p>
<pre class="brush:xml" style="font-size:75%">
&lt;filter&gt;
  &lt;filter-name&gt;TeeFilter&lt;/filter-name&gt;
  &lt;filter-class&gt;ch.qos.logback.access.servlet.TeeFilter&lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
  &lt;filter-name&gt;TeeFilter&lt;/filter-name&gt;
  &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;

&lt;servlet&gt;
  &lt;servlet-name&gt;ViewStatusMessages&lt;/servlet-name&gt;
  &lt;servlet-class&gt;ch.qos.logback.classic.ViewStatusMessagesServlet&lt;/servlet-class&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
  &lt;servlet-name&gt;ViewStatusMessages&lt;/servlet-name&gt;
  &lt;url-pattern&gt;/logbackStatus&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p style="text-decoration:underline;font-weight:bold">Test Specific Configuration</p>
<p>In our project&#8217;s <code>src/main/resources</code> we define a <code>logback.xml</code> file.<br />
In our project&#8217;s <code>src/test/resources</code> we define a <code>logback-test.xml</code> file.</p>
<p style="text-decoration:underline;font-weight:bold">Conditional Configuration</p>
<p>Logback uses <a href="http://docs.codehaus.org/display/JANINO/Home">Janino</a> allowing the ability to perform conditional configuration.  </p>
<p><em>Janino Maven Dependency</em></p>
<pre class="brush:xml" style="font-size:75%">
&lt;dependency&gt;
  &lt;groupId&gt;org.codehaus.janino&lt;/groupId&gt;
  &lt;artifactId&gt;janino&lt;/artifactId&gt;
  &lt;version&gt;2.6.1&lt;/version&gt;
&lt;/dependency&gt;
</pre>
<p><em>Conditional Operations</em></p>
<p><code></p>
<ul>
<li>boolean isDefined(String prop);</li>
<li>boolean isNull(String prop);</li>
<li>String p(String prop);</li>
<li>String property(String prop);</li>
</ul>
<p></code><br />
See: <a href="http://logback.qos.ch/apidocs/ch/qos/logback/core/joran/conditional/PropertyWrapperForScripts.html">PropertyWrapperForScripts JavaDoc</a> </p>
<pre class="brush:xml" style="font-size:75%">
&lt;if condition='isDefined("catalina.home")'&gt;
  &lt;then&gt;
    &lt;property name="log.dir" value="${catalina.home}"/&gt;
  &lt;/then&gt;
  &lt;else&gt;
    &lt;property name="log.dir" value="${user.dir}/logs"/&gt;
  &lt;/else&gt;
&lt;/if&gt;
</pre>
<p>The cool thing is that we can use Spring 3 environment profiles <code>spring.profiles.active</code>.  In the example below, the method <code>property()</code> or <code>p()</code> returns a String, so we can use String functions such as <code>contains()</code>.</p>
<pre class="brush:xml" style="font-size:75%">
&lt;if condition='property("spring.profiles.active").contains("dev")'&gt;
  &lt;then&gt;
    &lt;property name="log.dir" value="${catalina.home}"/&gt;
  &lt;/then&gt;
  &lt;else&gt;
    &lt;property name="log.dir" value="${user.dir}/logs"/&gt;
  &lt;/else&gt;
&lt;/if&gt;
</pre>
<p>Note: For testing, with Maven via the Jetty or Tomcat plugins, <code>${user.dir}</code> resolves to the project home.</p>
<p style="text-decoration:underline;font-weight:bold">Modular Configuration</p>
<p>We can configure multiple configuration files, effectively segmenting our configuration.  We could use a more detailed logging configuration for testing and a more conservative logging for production.</p>
<p><em>logback.xml</em></p>
<pre class="brush:xml" style="font-size:75%">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration debug="true" scan="true" scanPeriod="5 seconds"&gt;
  &lt;property resource="logconfig/logback.properties"/&gt;

  &lt;include resource="logconfig/headerconfig.xml"/&gt;

  &lt;if condition='property("spring.profiles.active").contains("dev")'&gt;
    &lt;then&gt;
      &lt;include resource="logconfig/springbeans.xml"/&gt;
      &lt;include resource="logconfig/hibernatefile.xml"/&gt;
    &lt;/then&gt;
    &lt;else&gt;
      &lt;include resource="logconfig/productionfile.xml"/&gt;
    &lt;/else&gt;
  &lt;/if&gt;

  &lt;include resource="logconfig/consolelog.xml"/&gt;

  &lt;root level="warn"&gt;
    &lt;appender-ref ref="console"/&gt;
  &lt;/root&gt;
&lt;/configuration&gt;
</pre>
<p><em>hibernatefile.xml</em></p>
<p>Included files use are wrapped with the <code>include</code> tag.</p>
<pre class="brush:xml" style="font-size:75%">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;included&gt;
  &lt;appender name="hibernatefile"
    class="ch.qos.logback.core.rolling.RollingFileAppender"&gt;
    &lt;file&gt;${log.dir}/${hibernate.logfile}.log&lt;/file&gt;
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"&gt;
      &lt;fileNamePattern&gt;${log.dir}/${hibernate.logfile}.%i.log.zip&lt;/fileNamePattern&gt;
      &lt;minIndex&gt;1&lt;/minIndex&gt;
      &lt;maxIndex&gt;6&lt;/maxIndex&gt;
    &lt;/rollingPolicy&gt;
    &lt;triggeringPolicy
      class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"&gt;
      &lt;maxFileSize&gt;50MB&lt;/maxFileSize&gt;
    &lt;/triggeringPolicy&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;%date %level - %msg%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;logger name="org.springframework.orm" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
  &lt;logger name="org.springframework.jdbc" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
  &lt;logger name="org.springframework.transaction" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
  &lt;logger name="org.hibernate.ejb" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
  &lt;logger name="org.hibernate.sql" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
  &lt;logger name="org.hibernate.tool.hbm2ddl" level="debug"&gt;
    &lt;appender-ref ref="hibernatefile" /&gt;
  &lt;/logger&gt;
&lt;/included&gt;
</pre>
<p><br/></p>
<h2>Summary</h2>
<ul>
<li>Do NOT use <code>System.out</code> or <code>System.err</code></li>
<li>Use SLF4j parameter placeholder <code>{}</code> instead of string concatenation, this eliminates the need for <code>isDebugEnabled()</code> around our debug logging</li>
<li>Always define the <code>Logger</code> as <code>private static final</code></li>
<li>Using SLF4j and Logback provides flexible, smart logging. We have tools that provide rich logging options for enterprise application development
<ul>
<li>Logback speaks natively to SLF4j</li>
<li>Java and Groovy configuration</li>
<li>Conditional Logging</li>
<li>Modular configuration</li>
<li>Access logging</li>
<li>Message filtering</li>
<li>Compression of rolled log files</li>
<li>Sifting Appenders by runtime attributes</li>
</ul>
</li>
</ul>
<p><br/></p>
<h2>Further Reading</h2>
<ul>
<li><a href="http://logback.qos.ch/">http://logback.qos.ch</a></li>
<li><a href="http://www.slf4j.org/">http://www.slf4j.org</a></li>
<li><a href="http://logging.apache.org/log4j/1.2/">http://logging.apache.org/log4j/1.2</a></li>
<li><a href="http://jorgecardoso.org/blog/index.php?/archives/116-java.util.logging-versus-System.out-performance.html">Logging vs System.out Performance</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/#logging">Enterprise Spring Best Practices Blog</a></li>
<li><a href="http://docs.codehaus.org/display/JANINO/Home">Janino</a></li>
</ul>
<p><br/></p>
<h2>Sources</h2>
<ul>
<li><a href="https://github.com/gordonad/spring-data-demos">Spring Data Demos with Profile Example &#8211; Profiles subproject</a></li>
<li><a href="https://github.com/gordonad/enterprise-spring-best-practices">Enterprise Spring Best Practices Samples</a></li>
</ul>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2013/03/27/sawing-through-the-java-loggers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Database Configuration with Spring 3.2 Environment Profiles</title>
		<link>http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/</link>
		<comments>http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/#comments</comments>
		<pubDate>Thu, 28 Feb 2013 19:05:46 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Annotations]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Data]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[apache derby]]></category>
		<category><![CDATA[autowired]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[derby]]></category>
		<category><![CDATA[di]]></category>
		<category><![CDATA[Environment]]></category>
		<category><![CDATA[h2]]></category>
		<category><![CDATA[h2 database]]></category>
		<category><![CDATA[h2database]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[hsql]]></category>
		<category><![CDATA[JPA]]></category>
		<category><![CDATA[junit]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[oracle]]></category>
		<category><![CDATA[ORM]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[profile]]></category>
		<category><![CDATA[Profiles]]></category>
		<category><![CDATA[spring 3.2]]></category>
		<category><![CDATA[Spring Data JPA]]></category>
		<category><![CDATA[spring framework]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1769</guid>
		<description><![CDATA[Database Configuration with Spring 3.2 Environment Profiles This is a followup to my previous blog Spring 3.1 Environment Profiles Let&#8217;s demonstrate how to configure an application to use different databases based on configuration. The code below is using Spring JavaConfig, &#8230; <a href="http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h2>
Database Configuration with Spring 3.2 Environment Profiles</h2>
<p>This is a followup to my previous blog <a href="http://gordondickens.com/wordpress/2012/06/12/spring-3-1-environment-profiles/" title="Spring 3.1 Environment Profiles">Spring 3.1 Environment Profiles</a></p>
<p>Let&#8217;s demonstrate how to configure an application to use different databases based on configuration.  The code below is using Spring JavaConfig, in lieu of XML config.  </p>
<p>Source Code: <a href="https://github.com/gordonad/spring-data-demos" title="Spring Data Demos with Profile Example">Spring Data Demos with Profile Example</a></p>
<hr/>
<h3>
Profiles</h3>
<p>Spring 3.2 has improved the environment-aware profiles feature.  Our applications can activate beans, at runtime, defined in specific profiles. For example to test different databases, we can use profiles such as Oracle, MySQL, HSQL, etc.</p>
<p>Let&#8217;s see how to configure a Spring application for multiple database vendor support to aid developers in testing with an in memory database (offline) before connecting to the enterprise database.<br />
</p>
<h3>Common JPA Configuration</h3>
<p>Since all of the classes will use JPA and Hibernate in these examples, there is clearly common configuration for all database vendors.</p>
<p>Common beans are typically <code>DataSource</code>, <code>TransactionManager</code>, <code>EntityManager</code> and <code>EntityManagerFactory</code>.</p>
<p>We&#8217;ll create configuration classes for the different database types in the package <code>com.gordondickens.orm.config</code></p>
<pre style="font-size:75%">
├── db
│   ├── JpaCommonConfig.java
│   ├── JpaDerbyClientConfig.java
│   ├── JpaDerbyEmbeddedConfig.java
│   ├── JpaH2EmbeddedConfig.java
│   ├── JpaHsqlEmbeddedConfig.java
│   ├── JpaMySqlEmbeddedConfig.java
│   ├── JpaOracleConfig.java
│   ├── JpaOracleJndiConfig.java
│   └── JpaPostgresqlConfig.java
└── support
    ├── DatabaseConfigProfile.java
    └── Hbm2ddlType.java
</pre>
<p><u><br />
<h4>JpaCommonConfig</h4>
<p></u></p>
<ul>
<li><code>@Configuration</code> &#8211; defines this class as a Spring Configuration class</li>
<li><code>@PropertySource</code> &#8211; loads in external properties into the <code>Environment</code></li>
<li><code>@Bean</code> &#8211; defines a Spring bean, where the bean name is defined by the method name and the type is defined by the return type</li>
<li><code>@Value</code> &#8211; uses SpEL (Spring Expression Language) to extract property values from the autowired <code>Environment</code>, note the pound sign &#8220;#&#8221; indicates a bean reference</li>
<li><code>getDatabaseDialect()</code> &#8211; is required to be implemented in concrete classes</li>
<li><code>getJpaProperties()</code> &#8211; is expected to be implemented in concrete classes</li>
<li>The getters will provide values from the environment, via the concrete Jpa config classes</li>
</ul>
<pre class="brush:java" style="font-size:75%">
package com.gordondickens.orm.config.db;

import org.hibernate.dialect.Dialect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Properties;

/**
 * Common Settings for JPA
 */
@Configuration
@PropertySource("classpath:/META-INF/spring/app-config.properties")
public abstract class JpaCommonConfig {
  public static final String UNDEFINED = "**UNDEFINED**";
  public static final String CONNECTION_CHAR_SET = "hibernate.connection.charSet";
  public static final String VALIDATOR_APPLY_TO_DDL = "hibernate.validator.apply_to_ddl";
  public static final String VALIDATOR_AUTOREGISTER_LISTENERS = "hibernate.validator.autoregister_listeners";

  @Autowired
  Environment environment;

  @Value("#{ environment['entity.package'] }")
  private String entityPackage = "com.gordondickens.orm.hibernate.domain";

  @Bean
  public abstract DataSource dataSource();

  @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);
    vendorAdapter.setDatabasePlatform(getDatabaseDialect().getName());
    vendorAdapter.setShowSql(true);

    LocalContainerEntityManagerFactoryBean factory =
        new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan(entityPackage);
    factory.setDataSource(dataSource());
    if (getJpaProperties() != null) {
      factory.setJpaProperties(getJpaProperties());
    }
    return factory;
  }

  @Bean
  public EntityManager entityManger() {
    return entityManagerFactory().getObject().createEntityManager();
  }

  @Bean
  public PlatformTransactionManager transactionManager() {
    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory().getObject());
    return txManager;
  }

  protected abstract Class&lt;? extends Dialect&gt; getDatabaseDialect();

  protected Properties getJpaProperties() {
    return null;
  }

  public String getDatabaseName() {
    return environment.getProperty("database.name", UNDEFINED);
  }

  public String getHost() {
    return environment.getProperty("database.host", UNDEFINED);
  }

  public String getPort() {
    return environment.getProperty("database.port", UNDEFINED);
  }

  public String getUrl() {
    return environment.getProperty("database.url", UNDEFINED);
  }

  public String getUser() {
    return environment.getProperty("database.username", UNDEFINED);
  }

  public String getPassword() {
    return environment.getProperty("database.password", UNDEFINED);
  }

  public String getDriverClassName() {
    return environment.getProperty("database.driverClassName", UNDEFINED);
  }

  public String getDialect() {
    return environment.getProperty("database.dialect", UNDEFINED);
  }

  public String getDatabaseVendor() {
    return environment.getProperty("database.vendor", UNDEFINED);
  }

  public String getHbm2ddl() {
    return environment.getProperty("database.hbm2ddl.auto", "none");
  }

  public String getHibernateCharSet() {
    return environment.getProperty("database.hibernateCharSet", "UTF-8");
  }

  public String getDatabaseValidationQuery() {
    return environment.getProperty("database.validation.query", UNDEFINED);
  }
}
</pre>
<p></p>
<h3>Concrete Database Configuration Classes</h3>
<p>Inherit from the JpaCommonConfig class to provide vendor specific configuration.</p>
<pre class="brush:java" style="font-size:75%">
package com.gordondickens.orm.config.db;

import com.gordondickens.orm.config.support.DatabaseConfigProfile;
import com.gordondickens.orm.config.support.Hbm2ddlType;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.cfg.ImprovedNamingStrategy;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;
import static java.lang.Boolean.TRUE;
import static org.hibernate.cfg.Environment.*;
import static org.hibernate.ejb.AvailableSettings.NAMING_STRATEGY;

/**
 * HSQL Embedded
 */
@Configuration
@Profile(DatabaseConfigProfile.HSQL_EMBEDDED)
@PropertySource("classpath:/META-INF/spring/hsql.properties")
public class JpaHsqlEmbeddedConfig extends JpaCommonConfig {

  @Override
  @Bean(destroyMethod = "close")
  public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(getDriverClassName());
    dataSource.setUrl(getUrl());
    dataSource.setUsername(getUser());
    dataSource.setPassword(getPassword());
    dataSource.setValidationQuery(getDatabaseValidationQuery());
    dataSource.setTestOnBorrow(true);
    dataSource.setTestOnReturn(true);
    dataSource.setTestWhileIdle(true);
    dataSource.setTimeBetweenEvictionRunsMillis(1800000);
    dataSource.setNumTestsPerEvictionRun(3);
    dataSource.setMinEvictableIdleTimeMillis(1800000);
    return dataSource;
  }

  @Override
  protected Properties getJpaProperties() {
    Properties properties = new Properties();
    properties.setProperty(HBM2DDL_AUTO, Hbm2ddlType.CREATE_DROP.toValue());
    properties.setProperty(GENERATE_STATISTICS, TRUE.toString());
    properties.setProperty(SHOW_SQL, TRUE.toString());
    properties.setProperty(FORMAT_SQL, TRUE.toString());
    properties.setProperty(USE_SQL_COMMENTS, TRUE.toString());
    properties.setProperty(CONNECTION_CHAR_SET, getHibernateCharSet());
    properties.setProperty(NAMING_STRATEGY, ImprovedNamingStrategy.class.getName());
    return properties;
  }

  @Override
  protected Class&lt;? extends Dialect&gt; getDatabaseDialect() {
    return HSQLDialect.class;
  }

  @Bean
  public DatabasePopulator databasePopulator(DataSource dataSource) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(true);
    populator.setIgnoreFailedDrops(true);
    // populator.addScript(new ClassPathResource("/sql/mydata-dml.sql"));
    try {
      populator.populate(dataSource.getConnection());
    } catch (SQLException ignored) {}
    return populator;
  }
}
</pre>
<p></p>
<h3>Testing</h3>
<p>JavaConfig allows us to configure Spring with or without XML configuration.  If we want to test beans that are defined in a Configuration class we configure our test with the <code>loader</code> and <code>classes</code> arguments of the <code>@ContextConfiguration</code> annotation.</p>
<p><u><br />
<h4>Test Context Configuration</h4>
<p></u><br />
Create a configuration class, bootstrapping the test context for the beans to be tested.</p>
<ul>
<li><code>@ComponentScan</code> &#8211; scans for annotated beans and entities.  Note that <code>@ComponentScan</code> will ignore auto-discovery of other <code>@Configuration</code> classes</li>
<li><code>@EnableJpaRepositories</code> &#8211; configures Spring-Data-JPA repository interfaces annotated with <code>@Repository</code></li>
<li><code>@EnableTransactionManagement</code> &#8211; proxies the <code>@Transactional</code> annotated classes</li>
</ul>
<pre class="brush:java" style="font-size:75%">
package com.gordondickens.orm.hibernate.config;

import com.gordondickens.orm.hibernate.domain.Employee;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Test Configuration
 */
@Configuration
@ComponentScan(basePackages = "com.gordondickens.orm.hibernate",
    excludeFilters = {@ComponentScan.Filter(Configuration.class)})
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.gordondickens.orm.hibernate.repository")
public class TestConfig {

  @Bean
  @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
  public Employee employee() {
    return new Employee();
  }
}
</pre>
<p><u><br />
<h4>JUnit Test</h4>
<p></u></p>
<ul>
<li><code>@ActiveProfiles</code> &#8211; sets the valid profiles for the test execution similar to using the environment variable <code>spring.profiles.active</code></li>
<li><code>@ContextConfiguration</code> &#8211; sets up the test context. Here we load in the test bootstrap class and the vendor specific JPA configuration classes</li>
</ul>
<pre class="brush:java" style="font-size:75%">
package com.gordondickens.orm.hibernate.domain;

import com.gordondickens.orm.config.db.JpaHsqlEmbeddedConfig;
import com.gordondickens.orm.config.support.DatabaseConfigProfile;
import com.gordondickens.orm.hibernate.config.TestConfig;
import com.gordondickens.orm.hibernate.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.samePropertyValuesAs;
import static org.junit.Assert.assertThat;

@ActiveProfiles(DatabaseConfigProfile.HSQL_EMBEDDED)

@Transactional
@ContextConfiguration(classes = {JpaHsqlEmbeddedConfig.class, TestConfig.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class EmployeeHsqlIntegrationTest {

  @Autowired
  EmployeeService employeeService;

  @Test
  public void testMarkerMethod() {
    Employee employee = new Employee();
    employee.setFirstName("Cletus");
    employee.setLastName("Fetus");

    employeeService.saveEmployee(employee);
    assertThat("Employee MUST exist", employee, notNullValue());
    assertThat("Employee MUST have PK", employee.getId(), notNullValue());

    Employee employee1 = employeeService.findEmployee(employee.getId());
    assertThat("Employee Must be Found by ID", employee1.getId(),
        samePropertyValuesAs(employee.getId()));
  }
}
</pre>
<h3>Summary</h3>
<p>Using the Profile feature, we can configure a database so run locally on an embedded database, such as Derby, HSQL, or H2.  Using profiles gives developers the ability to validate entity and ORM configuration before connecting to the enterprise database, such as Oracle.</p>
<p>The example could be tuned to Component Scan configuration classes, eliminating the explicit include of the vendor specific JPA config class.</p>
<h3>Sources</h3>
<p><a href="https://github.com/gordonad/spring-data-demos" title="Spring Data Demos with Profile Example">Spring Data Demos with Profile Example</a></p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2013/02/28/database-config-spring-3-2-environment-profiles/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Enterprise Spring Best Practices &#8211; Part 4 &#8211; Annotation Config</title>
		<link>http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/</link>
		<comments>http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/#comments</comments>
		<pubDate>Mon, 19 Nov 2012 01:02:13 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[annotation-config]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[component]]></category>
		<category><![CDATA[component scan]]></category>
		<category><![CDATA[dependency injection]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1662</guid>
		<description><![CDATA[Enterprise Spring Best Practices Series In part 4, Spring Annotation Configuration. In this edition of Enterprise Spring Best Practices, let&#8217;s look at annotations. Several of the annotations became available in Spring 2.5. Spring 3.0 added convenient annotation discovery mechanisms which &#8230; <a href="http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Enterprise Spring Best Practices Series</p>
<p>In part 4, Spring Annotation Configuration.</p>
<p>In this edition of Enterprise Spring Best Practices, let&#8217;s look at annotations.  Several of the annotations became available in Spring 2.5.  Spring 3.0 added convenient annotation discovery mechanisms which we&#8217;ll see here.</p>
<p>Annotations are available for Dependency Injection, Bean discovery and instantiation, post processing (required fields, initialization method, etc).</p>
<p>Annotations may or may NOT be discovered in java interfaces, refer to the documentation or JavaDoc for details on whether the annotation discovery mechanism will traverse upward in the class hierarchy.</p>
<p><br/></p>
<h2>Sections</h2>
<hr/>
<ul>
<li><a href="#decision">Annotation Style Decision</a></li>
<li><a href="#xmldiscovery">Annotation Discovery from XML</a></li>
<li><a href="#appconfig">Application Component Scanning</a></li>
<li><a href="#mvcconfig">MVC Component Scanning</a></li>
<li><a href="#bestpractices">Component Scanning Best Practices</a></li>
<li><a href="#reading">Further Reading</a></li>
<li><a href="#social">Social Me</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="decision">Annotation Style Decision</a></h2>
<hr/>
<!-- ******************************************** --><br />
Annotations help simplify configuration.  All annotations in Java 5 and above, require some discovery mechanism.</p>
<p>Within Spring, we have 3 strategies for bean discovery and dependency injection</p>
<ol>
<li>XML based discovery</li>
<li>JavaConfig</li>
<li>Hybrid Configuration</li>
</ol>
<p>Hybrid configuration is simply mixing standard XML <code>&lt;bean/&gt;</code> declarations with annotation methods discussed below.  In the next blog, I will discuss JavaConfig, so for now lets focus on XML based discovery of Annotations.</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="xmldiscovery">Annotation Discovery from XML</a></h2>
<hr/>
<!-- ******************************************** --><br />
All annotations REQUIRE a discovery directive. We MUST know which XML directives discover particular annotations, or the beans will not be processed.<br />
For Spring annotation discovery detail, see <a href="http://gordondickens.com/wordpress/2011/05/20/annotation-reference-for-spring-projects/">Annotation Reference for Spring Projects</a></p>
<h3>Option 1 &#8211; Register individual bean post processors</h3>
<p>There are several individual Bean Post Processors that can be registered to discover specific annotation categories</p>
<ul>
<li>RequiredAnnotationBeanPostProcessor &#8211; (<code>@Required</code>)</li>
<li>CommonAnnotationBeanPostProcessor &#8211; (<code>@PostConstruct, @PreDestroy, @Resource</code>, etc.)</li>
<li>AutowiredAnnotationBeanPostProcessor &#8211; (<code>@Autowired, @Value, @Inject</code>, etc.)</li>
<li>PersistenceAnnotationBeanPostProcessor  &#8211; (<code>@PersistenceUnit, @PersistenceContext</code>, etc.)</li>
</ul>
<h3>Option 2 &#8211; Use the <code>annotation-config</code> directive</h3>
<p>Automatically registers the Bean Post Processors above.</p>
<pre class="brush:xml">
  &lt;context:annotation-config/&gt;
</pre>
<h3>Option 3 &#8211; Use the <code>component-scan</code> directive</h3>
<p>Automatically registers the Bean Post Processors above AND scans for component annotations <code>@Component, @Repository, @Service, @Controller</code>, and more…</p>
<pre class="brush:xml">
  &lt;context:context:component-scan 
      base-package="com.gordondickens.enterprisespring"/&gt;
</pre>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="appconfig">Application Component Scanning</a></h2>
<hr/>
<!-- ******************************************** --><br />
Exclude configuration elements that are not part of the underlying application.  Controllers are part of the application that deals with the user interface but are not pertinent to Web Services.<br />
Within <code>applicationContext-bootstrap.xml</code></p>
<pre class="brush:xml">
&lt;context:component-scan 
  base-package="com.gordondickens.enterprisespring"&gt;
    
  &lt;context:exclude-filter
    expression="org.springframework.stereotype.Controller"
    type="annotation"/&gt;
&lt;/context:component-scan&gt;
</pre>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="mvcconfig">MVC Component Scanning</a></h2>
<hr/>
<!-- ******************************************** --><br />
Exclude components are not part of the entire application.  If our application serves UI clients and web service clients, only the base components should be discovered in the main application configuration.  We will discuss MVC configuration in a future blog.</p>
<p>Within <code>applicationContext-webmvc.xml</code></p>
<pre class="brush:xml">
&lt;context:component-scan 
  base-package="com.gordondickens.enterprisespring"
  use-default-filters="false"/&gt;

    &lt;context:include-filter 
      expression="org.springframework.stereotype.Controller" 
      type="annotation"/&gt;
&lt;/context:component-scan&gt;
</pre>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="bestpractices">Component Scanning Best Practices</a></h2>
<hr/>
<!-- ******************************************** --><br />
When Spring creates the application context, it aggregates all of the configuration into a single context, no matter how many configuration files or annotations are used.</p>
<ul>
<li>Component scanning should ONLY be configured in the bootstrap config file, not in every XML config file</li>
<li>Do NOT also include the <code>&lt;context:annotation-config/&gt;</code> directive, it is automatically included by component scan</li>
<li>Do NOT start scanning from &#8220;com&#8221; and/or &#8220;org&#8221;, as this will scan ALL sub packages in all of the project and jars for candidates!</li>
<li>Be as specific as possible with the packages</li>
<li>Do NOT cross application boundaries with <code>component-scan</code>
<ul>
<li>Create an <code>applicationContext-services.xml</code> for scanning services</li>
<li>Create an <code>applicationContext-persistence.xml</code> for persistence and entity beans</li>
<li>Create an <code>applicationContext-webmvc.xml</code> for persistence and entity beans</li>
<li>Create an <code>applicationContext-webservice.xml</code> for web service beans</li>
<li>Import these references into the <code>applicationContext-bootstrap.xml</code> to these elements</li>
</ul>
</li>
</ul>
<p>Why separate the discovery files into layer specific configuration?</p>
<ul>
<li>Unit testing is easier as discovery of beans is more specific</li>
<li>Allows the project to be separated into multiple Jar/Wars</li>
<li>Lowers risk of widely scoped discovery issues, overscanning and beans being replaced by multiple scanners</li>
</ul>
<p>For Spring annotation discovery detail, see <a href="http://gordondickens.com/wordpress/2011/05/20/annotation-reference-for-spring-projects/">Annotation Reference for Spring Projects</a></p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="reading">Further Reading</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li><a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank">Enterprise Spring Best Practices &#8211; Part 1 &#8211; Project Configuration</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank">Enterprise Spring Best Practices &#8211; Part 2 &#8211; Application Architecture</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank">Enterprise Spring Best Practices – Part 3 – XML Config</a></li>
<li><a href="https://github.com/gordonad/enterprise-spring-best-practices" target="_blank">Enterprise Spring Best Practices &#8211; Source Code</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/" target="_blank">FREE Spring Framework PDF (848 pages)</a></li>
<li><a href="http://maven.apache.org/" target="_blank">Apache Maven</a></li>
<li><a href="http://www.slf4j.org/" target="_blank">SLF4J</a></li>
<li><a href="http://logback.qos.ch/reasonsToSwitch.html" target="_blank">Logback</a></li>
<li><a href="http://gradle.org/" target="_blank">Gradle</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="social">Social Me</a></h2>
<hr/>
<!-- ******************************************** --><br />
<a href="http://twitter.com/gdickens" target="_blank">Twitter &#8211; twitter.com/gdickens</a><br />
<a href="http://linkedin.com/in/gordondickens" target="_blank">LinkedIn &#8211; linkedin.com/in/gordondickens</a><br />
<a href="http://github.com/gordonad" target="_blank">GitHub: github.com/gordonad</a><br />
<a href="mailto:gordon@gordondickens.com" target="_blank">gordon@gordondickens.com</a></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/11/18/enterprise-spring-best-practices-part-4-annotation-config/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maven 3 Code Analysis and Reporting</title>
		<link>http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/</link>
		<comments>http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/#comments</comments>
		<pubDate>Thu, 02 Aug 2012 17:05:03 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Maven]]></category>
		<category><![CDATA[cobertura]]></category>
		<category><![CDATA[javadoc]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[maven 3]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[reporting]]></category>
		<category><![CDATA[site]]></category>
		<category><![CDATA[sonar]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1697</guid>
		<description><![CDATA[If you have read any of my other blogs, you will know that I am a fan (and defender) of Maven 3. One of the biggest changes in Maven 3 was the reporting capabilities with the Maven Site Plugin. I &#8230; <a href="http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>If you have read any of my other blogs, you will know that I am a fan (and defender) of Maven 3.  One of the biggest changes in Maven 3 was the reporting capabilities with the <a href="http://maven.apache.org/plugins/maven-site-plugin/">Maven Site Plugin</a>.</p>
<p>I will show example configuration for the Site 3.1 plugin using <a href="http://en.wikipedia.org/wiki/Markdown">Markdown syntax</a> for the page content and the <a href="http://daringfireball.net/projects/markdown/">Markdown project at Daring Fireball</a>.</p>
<p>Most of us have multi projects to build.  When I was setting up the Site configuration, I had to keep this in consideration.  I ran into issues with aggregating reports, and AspectJ classes with <a href="http://cobertura.sourceforge.net/">Cobertura</a> for code test coverage.</p>
<h3>Old Config (a.k.a. things to forget)</h3>
<p>The OLD Maven <code>reporting</code> section.</p>
<pre class="brush:xml">
&lt;reporting/&gt;
</pre>
<h3>New Config</h3>
<p>The Maven Site 3.x plugin is a &#8220;container&#8221; for reporting plugins.</p>
<p>Here is a table of some of the more common open source plugins.</p>
<table>
<tr>
<th>Report</th>
<th>Description</th>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-javadoc-plugin/">Javadoc</a></td>
<td>Generates JavaDoc</td>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-jxr-plugin/">Java XRef</a></td>
<td>Cross reference report of project source code</td>
</tr>
<tr>
<td><a href="http://mojo.codehaus.org/taglist-maven-plugin/">Tag List</a></td>
<td>Reports on Tags such as @todo and //TODO</td>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-project-info-reports-plugin/">Project Info</a></td>
<td>A plethora of miscellaneous report: info, ci, dependencies, scm, plugins, etc.</td>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-checkstyle-plugin/">Check Style</a></td>
<td>Checks Code Style for Developers</td>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-surefire-plugin/">Surefire</a></td>
<td>Reports Test Results</td>
</tr>
<tr>
<td><a href="http://maven.apache.org/plugins/maven-pmd-plugin/">PMD</a></td>
<td>Source Code Analyzer</td>
</tr>
<tr>
<td><a href="http://mojo.codehaus.org/findbugs-maven-plugin/">FindBugs</a></td>
<td>Reports on common code mistakes and pitfalls</td>
</tr>
<tr>
<td><a href="http://mojo.codehaus.org/sonar-maven-plugin/">Sonar</a></td>
<td>Analysis and metrics on code over time</td>
</tr>
<tr>
<td><a href="http://cobertura.sourceforge.net/">Cobertura</a></td>
<td>Reports Test Coverage</td>
</tr>
<tr>
<td><a href="http://mojo.codehaus.org/versions-maven-plugin/">Versions</a></td>
<td>Reports on application and plugin versions, and any updates available</td>
</tr>
</table>
<h3>Configuration</h3>
<pre class="brush:xml">
...
&lt;properties&gt;
  &lt;maven.checkstyle.plugin&gt;2.7&lt;/maven.checkstyle.plugin&gt;
  &lt;maven.cobertura.plugin&gt;2.5.1&lt;/maven.cobertura.plugin&gt;
  &lt;maven.doxia.module.markdown.version&gt;1.3&lt;/maven.doxia.module.markdown.version&gt;
  &lt;maven.javadoc.plugin&gt;2.9&lt;/maven.javadoc.plugin&gt;
  &lt;maven.jxr.plugin&gt;2.3&lt;/maven.jxr.plugin&gt;
  &lt;maven.pmd.plugin&gt;2.7.1&lt;/maven.pmd.plugin&gt;
  &lt;maven.project.info.reports.plugin&gt;2.6&lt;/maven.project.info.reports.plugin&gt;
  &lt;maven.site.plugin&gt;3.2&lt;/maven.site.plugin&gt;
  &lt;maven.sonar.plugin&gt;3.3.1&lt;/maven.sonar.plugin&gt;
  &lt;maven.surefire.plugin&gt;2.12.4&lt;/maven.surefire.plugin&gt;
  &lt;maven.taglist.plugin&gt;2.4&lt;/maven.taglist.plugin&gt;
  &lt;maven.versions.plugin&gt;1.3.1&lt;/maven.versions.plugin&gt;
  &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
  &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
&lt;/properties&gt;
...
&lt;build&gt;
  &lt;plugins&gt;
    &lt;plugin&gt;
	&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
	&lt;artifactId&gt;maven-site-plugin&lt;/artifactId&gt;
	&lt;version&gt;${maven.site.plugin}&lt;/version&gt;
	&lt;executions&gt;
	    &lt;!-- used for multiproject builds --&gt;
		&lt;execution&gt;
			&lt;id&gt;attach-descriptor&lt;/id&gt;
			&lt;goals&gt;
				&lt;goal&gt;attach-descriptor&lt;/goal&gt;
			&lt;/goals&gt;
		&lt;/execution&gt;
	&lt;/executions&gt;
	&lt;configuration&gt;
		&lt;reportPlugins&gt;
        &lt;!-- Report Plugins go here --&gt;
		&lt;/reportPlugins&gt;
		&lt;locales&gt;en&lt;/locales&gt;
	&lt;/configuration&gt;
	&lt;dependencies&gt;
	    &lt;!-- To use the Markdown format --&gt;
		&lt;dependency&gt;
			&lt;groupId&gt;org.apache.maven.doxia&lt;/groupId&gt;
			&lt;artifactId&gt;doxia-module-markdown&lt;/artifactId&gt;
			&lt;version&gt;${maven.doxia.module.markdown.version}&lt;/version&gt;
		&lt;/dependency&gt;
	&lt;/dependencies&gt;
	&lt;/plugin&gt;
  &lt;/plugins&gt;
&lt;/build&gt;
...
</pre>
<p>Now add each plugin into the <code>reportPlugins</code> section just as you would any other dependency.</p>
<h3>Page Templates</h3>
<p>Maven will look for page templates in the <code>src/site</code> directory of the project.  If the project is a parent <code>pom</code> project, add the directory <code>src/site</code> to the root of the project.</p>
<p>Here is a sample directory layout:</p>
<pre class="brush:text;hightlight:[12,13,19,22]">
├── projectA
│   ├── pom.xml
│   └── src
│       ├── main
│       └── test
├── projectB
│   ├── pom.xml
│   └── src
│       ├── main
│       └── test
├── pom.xml
├── src
│   └── site
|       ├── markdown
|       │   ├── build.md
|       │   ├── index.md
|       │   └── services
|       │       └── persistence.md
|       ├── resources
|       │   └── images
|       │       └── technophile.png
|       └── site.xml
└── projectZ
    ├── pom.xml
    └── src
        ├── main
        └── test
</pre>
<p>Notice that <code>src</code> is at the same level as the top level pom.</p>
<p>Files:<br />
Line 24: <code>site.xml</code> defines the sites layout.</p>
<pre style="brush:xml;highlight:[17]">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/DECORATION/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/DECORATION/1.0.0
  http://maven.apache.org/xsd/decoration-1.0.0.xsd"&gt;

  &lt;body&gt;
    &lt;menu name="Overview"&gt;
      &lt;item name="Introduction" href="index.html"/&gt;
      &lt;item name="Building MyProject" href="build.html"/&gt;
    &lt;/menu&gt;

    &lt;menu name="Common Services"&gt;
      &lt;item name="Persistence Detail" href="services/persistence.html"/&gt;
    &lt;/menu&gt;

    &lt;menu ref="reports"/&gt;
  &lt;/body&gt;
&lt;/project&gt;
</pre>
<p>This generates a page with links for the index page, a build page and a persistence page.  Also, line 17: menu ref=&#8221;reports&#8221; is a special link for the report plugins.</p>
<p>The *.md pages will convert from Markdown format into HTML.  The build.md file might contain something like this:</p>
<pre style="brush:text;hightlight:[1, 6]">
![Technophile](images/technophile.png)

Building Core Spring
==========================

[Gordon Dickens](mailto:gordon@gordondickens.com)

-----

My Project
----------

This project infuses time, space and dimension into a convenient war file.
</pre>
<p>Line 1 is a reference to an image file.  NOTE: this has to be in the <code>site/resources</code> directory.<br />
Line 6 shows how to include a link or hyperlink.</p>
<h3>Complete Reporting Config</h3>
<pre class="brush:xml">
&lt;plugin&gt;
  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
  &lt;artifactId&gt;maven-site-plugin&lt;/artifactId&gt;
  &lt;version&gt;${maven.site.plugin}&lt;/version&gt;
  &lt;executions&gt;
    &lt;execution&gt;
      &lt;id&gt;attach-descriptor&lt;/id&gt;
      &lt;goals&gt;
        &lt;goal&gt;attach-descriptor&lt;/goal&gt;
      &lt;/goals&gt;
    &lt;/execution&gt;
  &lt;/executions&gt;
  &lt;configuration&gt;
   &lt;reportPlugins&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-surefire-report-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.surefire.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;outputDirectory&gt;${project.reporting.outputDirectory}/testresults&lt;/outputDirectory&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.javadoc.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;aggregate&gt;true&lt;/aggregate&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-checkstyle-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.checkstyle.plugin}&lt;/version&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-project-info-reports-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.project.info.reports.plugin}&lt;/version&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-jxr-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.jxr.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;aggregate&gt;true&lt;/aggregate&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;cobertura-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.cobertura.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;aggregate&gt;true&lt;/aggregate&gt;
        &lt;outputDirectory&gt;%{project.reporting.outputDirectory}/cobertura&lt;/outputDirectory&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
      &lt;artifactId&gt;maven-pmd-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.pmd.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;aggregate&gt;true&lt;/aggregate&gt;
        &lt;sourceEncoding&gt;${project.build.sourceEncoding}&lt;/sourceEncoding&gt;
        &lt;!-- The minimum tokens before a violation --&gt;
        &lt;minimumTokens&gt;100&lt;/minimumTokens&gt;
        &lt;!-- Turn off if no xref report --&gt;
        &lt;linkXRef&gt;true&lt;/linkXRef&gt;
        &lt;verbose&gt;true&lt;/verbose&gt;
        &lt;targetJdk&gt;${java.version}&lt;/targetJdk&gt;
        &lt;rulesets&gt;
          &lt;ruleset&gt;/rulesets/maven.xml&lt;/ruleset&gt;
          &lt;ruleset&gt;/rulesets/migrating_to_junit4.xml&lt;/ruleset&gt;
          &lt;ruleset&gt;/rulesets/design.xml&lt;/ruleset&gt;
          &lt;ruleset&gt;/rulesets/unusedcode.xml&lt;/ruleset&gt;
          &lt;ruleset&gt;/rulesets/typeresolution.xml&lt;/ruleset&gt;
        &lt;/rulesets&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;findbugs-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.findbugs.plugin}&lt;/version&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;versions-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.versions.plugin}&lt;/version&gt;
    &lt;/plugin&gt;
    &lt;plugin&gt;
      &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
      &lt;artifactId&gt;taglist-maven-plugin&lt;/artifactId&gt;
      &lt;version&gt;${maven.taglist.plugin}&lt;/version&gt;
      &lt;configuration&gt;
        &lt;aggregate&gt;true&lt;/aggregate&gt;
      &lt;/configuration&gt;
    &lt;/plugin&gt;
   &lt;/reportPlugins&gt;
  &lt;locales&gt;en&lt;/locales&gt;
  &lt;/configuration&gt;
  &lt;dependencies&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.apache.maven.doxia&lt;/groupId&gt;
      &lt;artifactId&gt;doxia-module-markdown&lt;/artifactId&gt;
      &lt;version&gt;${maven.doxia.module.markdown.version}&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/plugin&gt;
</pre>
<hr/>
<h3>Summary</h3>
<p>Wow, that&#8217;s a lot of config!  The configuration sample above has a bit of overlap.  Simple remove the report plugins that are not as important to you at the present time.</p>
<p>Watch out for the JXR plugin, this is a very time consuming report to generate.  If this becomes something you want to run infrequently, I recommend different Maven profiles, one with JXR and one without.</p>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/08/02/maven-3-code-analysis-and-reporting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enterprise Spring Framework Best Practices &#8211; Part 3 &#8211; XML Config</title>
		<link>http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/</link>
		<comments>http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/#comments</comments>
		<pubDate>Tue, 31 Jul 2012 01:23:35 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Java Util Logging]]></category>
		<category><![CDATA[SLF4J]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[java util logging]]></category>
		<category><![CDATA[slf4j]]></category>
		<category><![CDATA[spring framework]]></category>
		<category><![CDATA[System.err]]></category>
		<category><![CDATA[System.out]]></category>
		<category><![CDATA[xml configuration]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1496</guid>
		<description><![CDATA[Enterprise Spring Best Practices Series In part 3, Spring XML Configuration. The best thing about Spring is that there are several way to solve a problem, the worst thing about Spring is that there are several ways to solve a &#8230; <a href="http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Enterprise Spring Best Practices Series<br />
In part 3, Spring XML Configuration.</p>
<p>The best thing about Spring is that there are several way to solve a problem, the worst thing about Spring is that there are several ways to solve a problem!</p>
<p>One of the greatest challenges when using Spring is choosing the best way to implement solutions.  As most of us developers do, we hit Google or grab books on Spring, which can get us moving in the right direction.  Many times we find conflicting configurations between implementation approaches.  For Spring newcomers, this can be challenging and cause grievous mental confusion down the road.</p>
<p><br/></p>
<h2>Sections</h2>
<hr/>
<ul>
<li><a href="#namespaces">Spring Namespaces</a></li>
<li><a href="#bootstrap">One Bootstrap XML File</a></li>
<li><a href="#classpath">Always use <code>classpath</code> Prefix</a></li>
<li><a href="#naming">Bean Naming</a></li>
<li><a href="#di">Dependency Injection</a></li>
<li><a href="#thirdparty">Third Party Beans</a></li>
<li><a href="#properties">Externalize Properties</a></li>
<li><a href="#logging">Logging Beans</a></li>
<li><a href="#bestpractices">Best Practices</a></li>
<li><a href="#reading">Further Reading</a></li>
<li><a href="#social">Social Me</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="namespaces">Spring Namespaces</a></h2>
<hr/>
<!-- ******************************************** --></p>
<div style="font-weight:bold">No version numbers in schema references</div>
<p>Instead of:</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt;
...
&lt;/beans&gt;
</pre>
</div>
<p>USE This Config:</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd


http://www.springframework.org/schema/context

    http://www.springframework.org/schema/context/spring-context.xsd"&gt;
...
&lt;/beans&gt;
</pre>
</div>
<p>WHY?<br />
Spring automatically picks the highest version available from the project dependencies (jars).  As a project evolves, the Spring version will be updated, we won&#8217;t have to maintain all the XML config files to see the new features.</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="bootstrap">One Bootstrap XML File</a></h2>
<hr/>
<!-- ******************************************** --><br />
There are many examples of using multiple XML configuration files.  An application usually has several XML configuration files, but there should only be ONE bootstrap file.  This bootstrap file should use the <code>&lt;import resource=""/&gt;</code> to include other config files.</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="classpath">Classpath Prefix</a></h2>
<hr/>
<!-- ******************************************** --><br />
Always use <code>classpath:</code> prefix<br />
When importing resources, XML config, properties, etc.  Always use the <code>classpath:</code> or <code>classpath*:</code> prefix.<br />
This provides consistency and clarity to the location of the resource.  Not every feature of Spring behaves the same, <code>classpath:</code> guarantees consistency.<br />
The classpath is determined by the build tool and IDE.  Usually this is <code>src/main/java</code> for java code, <code>src/main/resources</code> for non-java dependencies and for tests, <code>src/test/java</code> for java code and <code>src/test/resources</code> for non-java resources.</p>
<p>Example:</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;import 
  resource="classpath:/META-INF/spring/applicationContext-security.xml"/&gt;
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="naming">Bean Naming</a></h2>
<hr/>
<!-- ******************************************** --><br />
The Spring Context is the container for the application&#8217;s beans.  Each bean is uniquely identified by its name.  The xml attribute &#8220;id&#8221; is most commonly used to define the bean&#8217;s name. The &#8220;id&#8221; attribute is great because it is, by XML Law, unique per file.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;bean id="accountService"
  class="com.gordondickens.services.AccountService/&gt;
</pre>
</div>
<p>However, if we want to use special symbols in the name or provide aliases to the name, we can use the Spring provided &#8220;name&#8221; attribute.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;bean name="accountService,services/account" 
  class="com.gordondickens.services.AccountService/&gt;
</pre>
</div>
<p>Spring 3.1 added the <code>profile</code> feature, providing the ability to configure beans by category or region.<br />
With 3.1, Spring overloads the XML &#8220;id&#8221; attribute allowing multiple beans with the same &#8220;id&#8221; in an XML file by profile.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd"&gt;

  &lt;beans profiles="dev,qa"&gt;
    &lt;bean id="dataSource" class="..."/&gt;
    &lt;bean id="messagingProvider" class="..."/&gt;
  &lt;/beans&gt;
  
  &lt;beans profiles="prod"&gt;
    &lt;bean id="dataSource" class="..."/&gt;
    &lt;bean id="messagingProvider" class="..."/&gt;
  &lt;/beans&gt;
&lt;/beans&gt;
</pre>
</div>
<p>For more detail on Spring 3.1 profiles, see my blog <a href="http://gordondickens.com/wordpress/2012/06/12/spring-3-1-environment-profiles/">Spring 3.1 Environment Profiles</a></p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="di">Dependency Injection</a></h2>
<hr/>
<!-- ******************************************** --><br />
Dependency Injection is one of the basic tenets of the Spring Framework. DI provides developers the ability to &#8220;wire together&#8221; bean relationships in configuration instead of coding the relationships.</p>
<p>The two ways to perform di are either by Constructor injection or Setter Injection.</p>
<p>In <a href="http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank">Enterprise Spring Best Practices &#8211; Part 2 &#8211; Application Architecture</a>, describes the layered application approach. In this layered approach, we can expect to inject beans together between layers.<br />
For example, wiring from the bottom up:</p>
<ol>
<li><code>DataSource</code>, the common JDBC class for database connectivity, is injected into our persistence beans</li>
<li>The persistence beans are injected into our service beans</li>
<li>The service beans are injected into our controller beans</li>
</ol>
<h3>Constructor Injection</h3>
<p>Constructor injection is performed using the <code>&lt;bean/&gt;</code> node <code>&lt;constructor-arg</code>.<br />
Thread safety, is a strong case for using constructors. Making beans immutable, is the cheapest thread-safety we can code.</p>
<p>In the following example, we see configuration of an in-memory HSQLDB database with an &#8220;id&#8221; of &#8220;dataSource&#8221;.  The bean <code>AccountRepositoryImpl</code> bean is injected with this implementation when Spring starts.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;bean id="accountRepository"
  class="com.gordondickens.repository.internal.AccountRepositoryImpl"&gt;
  &lt;constructor-arg ref="dataSource"/&gt;
&lt;/bean&gt;

&lt;!-- Spring's In-Memory DB Config, using HSQLDB --&gt;
&lt;!-- Note the HSQLDB driver must be in the project dependencies --&gt;
&lt;jdbc:embedded-database
  id="dataSource" type="HSQL"&gt;
  &lt;jdbc:script
    location="classpath:/mySchema.sql"/&gt;
  &lt;jdbc:script
    location="classpath:/mySampleData.sql"/&gt;
&lt;/jdbc:embedded-database&gt;
</pre>
</div>
<h3>Setter Injection</h3>
<p>Setter injection, provides the capability of injecting beans via a setter method. Traditionally, this has been the preferred choice for many developers, because the configuration is easier to read.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;bean id="accountRepository"
      class="com.gordondickens.repository.internal.AccountRepositoryImpl"&gt;
  &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="thirdparty">Third Party Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Any Java class can be used in the Spring framework.  Infrastructure beans, such as ActiveMQ&#8217;s <code>ConnectionFactory</code> or Oracle&#8217;s <code>OracleDataSource</code> is possible.</p>
<p>Third party beans, where we don&#8217;t have the source, or do not wish to tamper with the source, the choice for DI is made for us.</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="properties">Externalize Properties</a></h2>
<hr/>
<!-- ******************************************** --><br />
Deployment configuration requires setting environmental parameters, such as database connection properties.</p>
<p>Since XML can be brittle, it is best to externalize settings into property files.  This makes it easier for the deployment team to change resource configuration with less risk.</p>
<p>Spring provides a <code>PropertyPlaceholderConfigurer</code> for that purpose.</p>
<h3>Property Replacement Config</h3>
<div style="font-size:small">
<pre class="brush:xml">
&lt;context:property-placeholder
  location="classpath*:META-INF/spring/*.properties"/&gt;

&lt;bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close"&gt;
  &lt;property name="driverClassName"
    value="${database.driverClassName}"/&gt;
  &lt;property name="url"
    value="${database.url}"/&gt;
  &lt;property name="username"
    value="${database.username}"/&gt;
  &lt;property name="password"
    value="${database.password}"/&gt;
&lt;/bean&gt;
</pre>
</div>
<h3>Properties File</h3>
<div style="font-size:small">
<pre class="brush:text">
database.driverClassName=org.hsqldb.jdbcDriver
database.url=jdbc\:hsqldb\:mem\:mydb
database.username=sa
database.password=
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="logging">Logging Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Following up on <a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank">Enterprise Spring Best Practices &#8211; Part 1 &#8211; Project Configuration</a> logging configuration.</p>
<h3>Java Util Logging</h3>
<p>To Enable handling of <code>java.util.logging</code> classes with SLF4J. Register the following in your Spring configuration:</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;!-- Enable handling of java.util.logging through SLF4J --&gt;
&lt;bean id="slf4JBridgeHandler" class="org.slf4j.bridge.SLF4JBridgeHandler"
  init-method="removeHandlersForRootLogger"/&gt;
&lt;bean class="org.slf4j.bridge.SLF4JBridgeHandler"
  init-method="install"
  depends-on="slf4JBridgeHandler"/&gt;
</pre>
</div>
<h3>System.out and System.err</h3>
<p>To Enable handling of <code>System.out</code> and <code>System.err</code> messages.  Register the following in your Spring configuration:</p>
<p>NOTE: This is NOT recommended for ongoing development, but for migrating poor code to use logging.</p>
<div style="font-size:small">
<pre class="brush:xml">
&lt;!-- System.out.println &amp; System.err.println handling through SLF4J --&gt;
&lt;bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"&gt;
  &lt;property name="targetClass" value="uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J"/&gt;
  &lt;property name="staticMethod"
      value="uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J.sendSystemOutAndErrToSLF4J"/&gt;
  &lt;property name="arguments"&gt;
    &lt;list&gt;
      &lt;!-- Set log level for System.out --&gt;
      &lt;util:constant 
        static-field="uk.org.lidalia.sysoutslf4j.context.LogLevel.DEBUG"/&gt;
      &lt;!-- Set log level for System.err --&gt;
      &lt;util:constant
        static-field="uk.org.lidalia.sysoutslf4j.context.LogLevel.ERROR"/&gt;
    &lt;/list&gt;
  &lt;/property&gt;
&lt;/bean&gt;
</pre>
</div>
<h3>Maven Dependency for SysOutOverSLF4J</h3>
<div style="font-size:small">
<pre class="brush:xml">
&lt;dependency&gt;
  &lt;groupId&gt;uk.org.lidalia&lt;/groupId&gt;
  &lt;artifactId&gt;sysout-over-slf4j&lt;/artifactId&gt;
  &lt;version&gt;1.0.2&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="bestpractices">Best Practices</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li>DO NOT use version numbers with the Spring schema namespaces</li>
<li>Always use <code>classpath:/</code> prefix for consist resource referencing</li>
<li>Always use a single XML config file to bootstrap the application or tests</li>
<li>Use the XML &#8220;id&#8221; attribute to identify a bean</li>
<li>Use Constructor injection to promote thread safety</li>
<li>Use Properties for configurable resources</li>
<li>DO NOT use the SysOutOverSLF4J for anything other than migration</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="reading">Further Reading</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li><a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank">Enterprise Spring Best Practices &#8211; Part 1 &#8211; Project Configuration</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank">Enterprise Spring Best Practices &#8211; Part 2 &#8211; Application Architecture</a></li>
<li><a href="https://github.com/gordonad/enterprise-spring-best-practices" target="_blank">Enterprise Spring Best Practices &#8211; Source Code</a></li>
<li><a href="http://www.slf4j.org/" target="_blank">SLF4J</a></li>
<li><a href="http://projects.lidalia.org.uk/sysout-over-slf4j/">SysOut Over SLF4J</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/" target="_blank">FREE Spring Framework PDF (848 pages)</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="social">Social Me</a></h2>
<hr/>
<!-- ******************************************** --><br />
<a href="http://twitter.com/gdickens" target="_blank">Twitter &#8211; twitter.com/gdickens</a><br />
<a href="http://linkedin.com/in/gordondickens" target="_blank">LinkedIn &#8211; linkedin.com/in/gordondickens</a><br />
<a href="http://github.com/gordonad" target="_blank">GitHub: github.com/gordonad</a><br />
<a href="mailto:gordon@gordondickens.com" target="_blank">gordon@gordondickens.com</a></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Mac OSX Mountain Lion &#8211; Git SVN Error</title>
		<link>http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/</link>
		<comments>http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/#comments</comments>
		<pubDate>Thu, 26 Jul 2012 02:05:26 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[10.8]]></category>
		<category><![CDATA[Apple]]></category>
		<category><![CDATA[HomeBrew]]></category>
		<category><![CDATA[Mountain Lion]]></category>
		<category><![CDATA[OSX]]></category>
		<category><![CDATA[ac_nonexistent.h]]></category>
		<category><![CDATA[brew install]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[git svn]]></category>
		<category><![CDATA[graphwiz]]></category>
		<category><![CDATA[mariadb]]></category>
		<category><![CDATA[mountain lion]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[os x]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[osx10.8.xctoolchain]]></category>
		<category><![CDATA[svn]]></category>
		<category><![CDATA[SVN/Core.pm]]></category>
		<category><![CDATA[xctoolchain]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1615</guid>
		<description><![CDATA[I ran into this issue just after upgrading to Mac OSX Mountain Lion 10.8 Can't locate SVN/Core.pm in @INC (@INC contains: /Applications/Xcode.app/Contents/Developer/usr/share/git-core/perl /usr/../Library/Perl/5.12/darwin-thread-multi-2level /usr/share/git-core/perl /Library/Perl/5.12/darwin-thread-multi-2level /Library/Perl/5.12 /Network/Library/Perl/5.12/darwin-thread-multi-2level /Network/Library/Perl/5.12 /Library/Perl/Updates/5.12.4 /System/Library/Perl/5.12/darwin-thread-multi-2level /System/Library/Perl/5.12 /System/Library/Perl/Extras/5.12/darwin-thread-multi-2level /System/Library/Perl/Extras/5.12 .) at /usr/libexec/git-core/git-svn line 61. I found &#8230; <a href="http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I ran into this issue just after upgrading to Mac OSX Mountain Lion 10.8</p>
<pre style="font-size:xx-small">
Can't locate SVN/Core.pm in @INC (@INC contains: 
/Applications/Xcode.app/Contents/Developer/usr/share/git-core/perl 
/usr/../Library/Perl/5.12/darwin-thread-multi-2level 
/usr/share/git-core/perl /Library/Perl/5.12/darwin-thread-multi-2level 
/Library/Perl/5.12 /Network/Library/Perl/5.12/darwin-thread-multi-2level 
/Network/Library/Perl/5.12 /Library/Perl/Updates/5.12.4 
/System/Library/Perl/5.12/darwin-thread-multi-2level 
/System/Library/Perl/5.12 /System/Library/Perl/Extras/5.12/darwin-thread-multi-2level 
/System/Library/Perl/Extras/5.12 .) at /usr/libexec/git-core/git-svn line 61.
</pre>
<p>I found this blog: <a href="http://lifeandcode.net/2012/02/using-git-svn-on-os-x-10-8-developer-preview/">http://lifeandcode.net/2012/02/using-git-svn-on-os-x-10-8-developer-preview/</a></p>
<p>1. Update to XCode 4.4!<br />
2. Add this to your shell script</p>
<pre style="font-size:xx-small">
export PERL5LIB="/Applications/Xcode.app/Contents/Developer/Library/Perl/5.12/darwin-thread-multi-2level"
</pre>
<hr/>
<h3>UPDATE:  28-Jul-12</h3>
<ul>
<li><a href="https://developer.apple.com/downloads/index.action?name=for%20Xcode%20-">Install XCode Command Line Tools</a></li>
<li>Run this command: <code>sudo ln -s /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain /Applications/Xcode.app/Contents/Developer/Toolchains/OSX10.8.xctoolchain</code></li>
</ul>
<hr/>
<h3>UPDATE: 30-Jul-12</h3>
<p>Issue with installing <a href="http://mariadb.org">MariaDB</a> (better fork of MySql).  <a href=" https://github.com/mxcl/homebrew/issues/12368">This link indicates a similar issue with Graphwiz</a>.<br />
ERROR: <code>"fatal error: 'ac_nonexistent.h' file not found"</code></p>
<ul>
<li><code>export HOMEBREW_MAKE_JOBS=1</code></li>
<li><code>brew install -vd mariadb</code></li>
</ul>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/07/25/mac-osx-mountain-lion-git-svn-error/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Enterprise Spring Best Practices – Part 2 – Application Architecture</title>
		<link>http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/</link>
		<comments>http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/#comments</comments>
		<pubDate>Mon, 09 Jul 2012 02:30:25 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[apring]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[enterprise]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1604</guid>
		<description><![CDATA[Our application components break down into two fundamental categories, the System and Problem Domains. System Domain &#8211; infrastructure components, the plumbing, this is Spring&#8217;s sweet spot! Problem Domain &#8211; business components, typically use-case driven, this is what most of developers &#8230; <a href="http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div style="font-weight:bold"Enterprise Spring Best Practices Series<br />
In part 2, Application Architecture.</div>
<p>This blog presents a look at the overall application components and architecture.</p>
<p><br/></p>
<h2>Sections</h2>
<hr/>
<ul>
<li><a href="#domains">Application Domain</a></li>
<li><a href="#layers">Application Layers</a></li>
<li><a href="#controller">Controller Beans</a></li>
<li><a href="#service">Service Beans</a></li>
<li><a href="#repository">Repository Beans</a></li>
<li><a href="#dto">Data Transfer Beans</a></li>
<li><a href="#conversion">Conversion Beans</a></li>
<li><a href="#reading">Further Reading</a></li>
<li><a href="#social">Social Me</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="domains">Application Domains</a></h2>
<hr/>
<!-- ******************************************** --><br />
Our application components break down into two fundamental categories, the System and Problem Domains.</p>
<ul>
<li>System Domain &#8211; infrastructure components, the plumbing, this is Spring&#8217;s sweet spot!</li>
<li>Problem Domain &#8211; business components, typically use-case driven, this is what most of developers are paid to solve</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="layers">Application Layers</a></h2>
<hr/>
<!-- ******************************************** --><br />
Application components (beans) should be separated into distinct layers, and categories.</p>
<p><a href="http://gordondickens.com/wordpress/wp-content/uploads/2012/07/Spring-App-Layers.png"><br />
  <img src="http://gordondickens.com/wordpress/wp-content/uploads/2012/07/Spring-App-Layers.png" alt="" title="Spring App Layers" width="499" height="663" class="aligncenter size-full wp-image-1617" /><br />
</a><br />
<br/></p>
<div style="font-weight:bold">Bean Layers</div>
<ol>
<li>Controllers (for MVC, System Domain)</li>
<li>Services (Problem Domain)</li>
<li>Repository (System Domain)</li>
</ol>
<div style="font-weight:bold">Other Bean Categories</div>
<ul>
<li>Data Transfer Objects (Problem Domain)</li>
<li>System Functions (System Domain)</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="controller">Controller Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
More on Controllers in an upcoming blog on Enterprise Spring Best Practices MVC blog &#8211; TBD</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="service">Service Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Service Beans are Problem Domain components.  These are the MOST significant in the application.  Service beans are the Fundamental component of SOA.</p>
<ul>
<li>These are POJOs</li>
<li>Always defined from interfaces</li>
<li>NEVER include infrastructure components</li>
<li>NO <code>import</code> of Spring or utility libraries</li>
<li>NO infrastructure annotations</li>
<li>Always declare transaction boundaries by public functions</li>
<li>Create implementation/concrete classes in a sub-package named <code>internal</code>
</ul>
<p>Spring annotations can be very useful for services, useful annotations are @Service and @Transactional.  To abstract away the infrastructure from the business services, create a project specific meta annotation.</p>
<div style="font-weight:bold">Custom Meta Annotation</div>
<pre class="brush:java">
package com.gordondickens.service.annotation;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Service
@Transactional
public @interface AppService {
    String value() default "";
}
</pre>
<div style="font-weight:bold">Meta Annotation Use</div>
<pre class="brush:java">
...
@AppService
public class MyClass() {
  ...
}
</pre>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="repository">Repository Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Repository beans are in the System Domain.  More on this in Enterprise Spring Best Practices ORM blog &#8211; TBD</p>
<ul>
<li>DO NOT contain business logic</li>
<li>Do use Spring and JPA annotations</li>
<li>Should be considered disposable</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="dto">Data Transfer Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Data Transfer Objects (DTO) are the fundamental objects in and out of our system.  DTOs are simple public POJOs that receive and send data as a logical set.</p>
<ul>
<li>Always Public Beans</li>
<li>Annotate with JAXB2 Annotations</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="conversion">Conversion Beans</a></h2>
<hr/>
<!-- ******************************************** --><br />
Spring provides a rich conversion registry at it&#8217;s core.  The conversion service in Spring is based on the original Bean Specification <code>PropertyEditor</code>.</p>
<p><code>PropertyEditor</code>s are focussed on String data into and out of our application.</p>
<p>The Spring class <code>org.springframework.beans.PropertyEditorRegistrySupport</code> shows the built in String &lt;&#8211;&gt; object classes. Which we use, usually without knowledge, in our applications.  When we configure our applications with XML and send in property values, Spring uses reflection to determine the argument type, if that type is not a String, Spring looks for a PropertyEditor that can convert from String to the target type.  We also can create our own PropertyEditor&#8217;s and register them for types such as US Social Security Number or Telephone Number.  See: <a href="http://manning.com/walls4">Craig Wall&#8217;s Spring in Action, 3rd Ed</a> for examples.</p>
<ul>
<li>Primitive wrapper types: <code>Long</code>, <code>Integer</code>, etc</li>
<li>Collection types: <code>List</code>, <code>Property</code>, <code>Set</code>, <code>Map</code>, etc.</li>
<li>Arrays</li>
<li>Utility types: <code>URL</code>, <code>TimeZone</code>, <code>Locale</code>, etc.</li>
</ul>
<p>Spring 3.0 introduced the Conversion service providing us the ability to register a conversion service for object &lt;&#8211;&gt; other conversion.  To use the conversion registry, we can register a conversion class that will automatically convert to/from MyObject &lt;&#8211;&gt; MyOtherObject.  See <a href="http://gordondickens.com/wordpress/2010/09/30/using-spring-3-0-custom-type-converter/">Using Spring Customer Type Converter Blog</a>.</p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="reading">Further Reading</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li><a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank">Enterprise Spring Best Practices &#8211; Part 1</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank">Enterprise Spring Best Practices &#8211; XML Configuration &#8211; Part 3</a></li>
<li><a href="https://github.com/gordonad/enterprise-spring-best-practices" target="_blank">Enterprise Spring Best Practices &#8211; Source Code</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/" target="_blank">FREE Spring Framework PDF (848 pages)</a></li>
<li><a href="http://manning.com/walls4">Craig Wall&#8217;s Spring in Action, 3rd Ed</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="social">Social Me</a></h2>
<hr/>
<!-- ******************************************** --><br />
<a href="http://twitter.com/gdickens" target="_blank">Twitter &#8211; twitter.com/gdickens</a><br />
<a href="http://linkedin.com/in/gordondickens" target="_blank">LinkedIn &#8211; linkedin.com/in/gordondickens</a><br />
<a href="http://github.com/gordonad" target="_blank">GitHub: github.com/gordonad</a><br />
<a href="mailto:gordon@gordondickens.com" target="_blank">gordon@gordondickens.com</a></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enterprise Spring Best Practices &#8211; Part 1 &#8211; Project Config</title>
		<link>http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/</link>
		<comments>http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/#comments</comments>
		<pubDate>Wed, 04 Jul 2012 03:29:27 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Jakarta Commons Logging]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Util Logging]]></category>
		<category><![CDATA[Jetty]]></category>
		<category><![CDATA[Log4J]]></category>
		<category><![CDATA[LogBack]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[Maven]]></category>
		<category><![CDATA[SLF4J]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[STS]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tomcat]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[Logback]]></category>
		<category><![CDATA[logging]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[slf4j]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1501</guid>
		<description><![CDATA[Enterprise Spring Best Practices Series In part 1, let&#8217;s review project structure and configuration. Sections Project Directories Project Dependencies Smart Logging Running with Jetty and Tomcat Spring Configuration Files Complete Maven Config Valuable Maven Commands Further Reading Social Me Project &#8230; <a href="http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Enterprise Spring Best Practices Series<br />
In part 1, let&#8217;s review project structure and configuration.</p>
<p><br/></p>
<h2>Sections</h2>
<hr/>
<ul>
<li><a href="#directories">Project Directories</a></li>
<li><a href="#dependencies">Project Dependencies</a></li>
<li><a href="#logging">Smart Logging</a></li>
<li><a href="#jetty">Running with Jetty and Tomcat</a></li>
<li><a href="#spring">Spring Configuration Files</a></li>
<li><a href="#maven">Complete Maven Config</a></li>
<li><a href="#maventips">Valuable Maven Commands</a></li>
<li><a href="#reading">Further Reading</a></li>
<li><a href="#social">Social Me</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="directories">Project Directories</a></h2>
<hr/>
<!-- ******************************************** --></p>
<div style="font-weight:bold">Production</div>
<ul>
<li><code>src/main/java</code> &#8211; Java Source code packages and classes</li>
<li><code>src/main/resources</code> &#8211; NON-Java Resources, such as property files and Spring configuration</li>
</ul>
<div style="font-weight:bold">Test</div>
<ul>
<li><code>src/test/java</code> &#8211; Test Source code packages and classes</li>
<li><code>src/test/resources</code> &#8211; NON-Java Resources, such as property files and Spring configuration</li>
</ul>
<p>Project Structure Example</p>
<div style="font-size:smaller">
<pre class="brush:text">
── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── gordondickens
    │   │           └── sample
    │   │               ├── domain
    │   │               │   └── MyDomain.java
    │   │               ├── repository
    │   │               │   └── MyDomainRepository.java
    │   │               ├── service
    │   │               │   ├── MyDomainService.java
    │   │               │   └── internal
    │   │               │       └── MyDomainServiceImpl.java
    │   │               └── web
    │   │                   └── MyDomainController.java
    │   ├── resources
    │   │   ├── META-INF
    │   │   │   └── spring
    │   │   │       ├── applicationContext.xml
    │   │   │       └── database.properties
    │   │   ├── logback-access.xml
    │   │   └── logback.xml
    │   └── webapp
    │       ├── WEB-INF
    │       │   ├── classes
    │       │   ├── i18n
    │       │   ├── layouts
    │       │   ├── spring
    │       │   │   └── webmvc-config.xml
    │       │   ├── views
    │       │   │   ├── myDomain
    │       │   │   │   ├── create.jsp
    │       │   │   │   ├── list.jsp
    │       │   │   │   ├── show.jsp
    │       │   │   │   └── update.jsp
    │       │   │   ├── dataAccessFailure.jsp
    │       │   │   ├── index.jsp
    │       │   │   ├── resourceNotFound.jsp
    │       │   │   ├── uncaughtException.jsp
    │       │   │   └── views.xml
    │       │   └── web.xml
    │       ├── images
    │       └── styles
    ├── site
    │   ├── apt
    │   ├── fml
    │   ├── site.xml
    │   └── xdoc
    └── test
        ├── java
        │   └── com
        │       └── gordondickens
        │           └── sample
        │               └── service
        │                   └── MyDomainServiceTests.java
        └── resources
            ├── com
            │   └── gordondickens
            │       └── sample
            │           └── service
            │               └── MyDomainServiceTests-context.xml
            └── logback-test.xml
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="dependencies">Project Dependencies</a></h2>
<hr/>
<!-- ******************************************** --><br />
I am a big fan of Maven, it provides a consistent build structure and numerous plugins.  Gradle is emerging as an alternative Groovy-based build tool, which supports the Maven structure.  If you are still using Ant, I urge you to move to a more robust build tool such as Maven or Gradle.  One of the challenges of enterprise build tools is managing transitive dependencies, here are some recommendations to ease these challenges.</p>
<div style="font-weight:bold">Dependency Versions</div>
<ul>
<li>DO NOT put version numbers below the <code>&lt;properties/&gt;</code> section, this will make it easier to upgrade and test newer versions.</li>
<li>DO include version numbers for ALL plugins! Do not rely on Maven&#8217;s built in Super Pom plugin versions!</li>
</ul>
<div style="font-weight:bold">Dependency Management</div>
<ul>
<li>USE Maven&#8217;s <code>&lt;DependencyManagement&gt;</code> section to control implicit and explicit versions!  Transitive dependencies will be resolved by those included in this section.</li>
</ul>
<div style="font-weight:bold">Enforcer Plugin</div>
<p>Prohibit the direct or indirect inclusion of incompatible and/or legacy jars.  For example, SLF4J 1.5, 1.6 and SLF4J 1.7 do not work together, therefore we need to prohibit the project from building with mixed dependency versions.  Spring is used by many open source projects, some reference older versions of Spring jars, so we want to control which Spring jar versions are inluded in our build.</p>
<p>Enforcer Example</p>
<ul>
<li>Ensures Java 1.6</li>
<li>Ensures Maven 2.2.1 to 3.0.x</li>
<li>Ensures Spring Jars 3.1 or greater</li>
<li>Prohibits old <code>javassist</code>, should be <code>org.javassist</code></li>
<li>Ensures no <code>commons-logging</code> or <code>commons-logging-api</code> dependencies</li>
<li>Ensures no <code>log4j</code> dependencies</li>
<li>Ensures no <code>SLF4J</code> 1.5 or 1.6 dependencies</li>
<li>Prohibits old <code>hsqldb</code>, should be <code>org.hsqldb</code></li>
<li>Prohibits old <code>aspectj</code>, should be <code>org.aspectj</code></li>
</ul>
<div  style="font-size:smaller">
<pre class="brush:xml">
&lt;properties&gt;
...
  &lt;java.version&gt;1.6&lt;/java.version&gt;
...
  &lt;maven.enforcer.plugin&gt;1.2&lt;/maven.enforcer.plugin&gt;
  &lt;maven.version.range&gt;[2.2.1,3.1.0)&lt;/maven.version.range&gt;
...
&lt;/properties&gt;

&lt;plugin&gt;
  &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
  &lt;artifactId&gt;maven-enforcer-plugin&lt;/artifactId&gt;
  &lt;version&gt;${maven.enforcer.plugin}&lt;/version&gt;
  &lt;executions&gt;
    &lt;execution&gt;
      &lt;id&gt;enforce-banned-dependencies&lt;/id&gt;
      &lt;goals&gt;
        &lt;goal&gt;enforce&lt;/goal&gt;
      &lt;/goals&gt;
      &lt;configuration&gt;
        &lt;rules&gt;
          &lt;bannedDependencies&gt;
            &lt;searchTransitive&gt;true&lt;/searchTransitive&gt;
            &lt;excludes&gt;
              &lt;exclude&gt;javassist:javassist&lt;/exclude&gt;
              &lt;exclude&gt;commons-logging&lt;/exclude&gt;
              &lt;exclude&gt;aspectj:aspectj*&lt;/exclude&gt;
              &lt;exclude&gt;hsqldb:hsqldb&lt;/exclude&gt;
              &lt;exclude&gt;log4j:log4j&lt;/exclude&gt;
              &lt;exclude&gt;org.slf4j:1.5*&lt;/exclude&gt;
              &lt;exclude&gt;org.springframework:2.*&lt;/exclude&gt;
              &lt;exclude&gt;org.springframework:3.0.*&lt;/exclude&gt;
            &lt;/excludes&gt;
          &lt;/bannedDependencies&gt;
          &lt;requireMavenVersion&gt;
            &lt;version&gt;${maven.version.range}&lt;/version&gt;
          &lt;/requireMavenVersion&gt;
          &lt;requireJavaVersion&gt;
            &lt;version&gt;${java.version}&lt;/version&gt;
          &lt;/requireJavaVersion&gt;
        &lt;/rules&gt;
        &lt;fail&gt;true&lt;/fail&gt;
      &lt;/configuration&gt;
    &lt;/execution&gt;
  &lt;/executions&gt;
&lt;/plugin&gt;
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="logging">Smart Logging</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li>NEVER use <code>System.out</code></li>
<li>NEVER use <code>System.err</code></li>
<li>ALWAYS use SLF4J</li>
<li>ALWAYS use Logback</li>
<li>Prohibit Apache Commons Logging (JCL) aka Jakarta Commons Logging</li>
<li>Prohibit Java Util Logging (JUL)</li>
</ul>
<p>Classes that use logging should include the following config for SLF4J (not log4j, not jcl, not jul, not logback):</p>
<div  style="font-size:smaller">
<pre class="brush:java; highlight:[5,6]">
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
public class MyClass {
  private static final Logger logger =
    LoggerFactory.getLogger(MyClass.class);
...
}
</pre>
</div>
<p>In the example below, SLF4J provides jars to route JCL and JUL logging through <code>jcl-over-slf4j</code> and <code>jul-to-slf4j</code>.  Spring uses JCL, so we need to use <code>jcl-over-slf4j</code> to handle Spring specific logged messages.</p>
<div  style="font-size:smaller">
<pre class="brush:xml">
&lt;properties&gt;
...
  &lt;logback.version&gt;1.0.10&lt;/logback.version&gt;
...
  &lt;slf4j.version&gt;1.7.4&lt;/slf4j.version&gt;
...
&lt;/properties&gt;

...

&lt;dependencies&gt;
...
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
  &lt;/dependency&gt;
...
&lt;/dependencies&gt;

...

&lt;dependencyManagement&gt;
  &lt;dependencies&gt;
...
   &lt;!-- Logging with SLF4J &amp; LogBack --&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-core&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-access&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
  &lt;/dependency&gt;
...
  &lt;/dependencies&gt;
&lt;/dependencyManagement&gt;
</pre>
</div>
<div style="font-weight:bold">Logging Configuration Files</div>
<ul>
<li><code>src/main/resources/logback.xml</code></li>
</ul>
<div  style="font-size:smaller">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration&gt;

  &lt;contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"&gt;
    &lt;resetJUL&gt;true&lt;/resetJUL&gt;
  &lt;/contextListener&gt;

  &lt;!-- To enable JMX Management --&gt;
  &lt;jmxConfigurator/&gt;

  &lt;appender name="console" class="ch.qos.logback.core.ConsoleAppender"&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;%.-1level|%-40.40logger{0}|%msg%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;logger name="com.mycompany.myapp" level="debug" /&gt;
  &lt;logger name="org.springframework" level="info" /&gt;

  &lt;logger name="org.springframework.beans" level="debug" /&gt;

  &lt;root level="warn"&gt;
    &lt;appender-ref ref="console" /&gt;
  &lt;/root&gt;
&lt;/configuration&gt;
</pre>
</div>
<p><br/></p>
<ul>
<li><code>src/main/resources/logback-test.xml</code></li>
</ul>
<p>Same configuration as production code, that will only be used for tests, usually for adding more log detail.</p>
<p><br/></p>
<ul>
<li><code>src/main/resources/logback-access.xml</code></li>
</ul>
<p>Configuration for server access logs. <code>HTTPRequest</code> and <code>HTTPResponses</code> messages can be displayed and/or logged When used with Logback TeeFilter in web.xml &#8211; GREAT for RESTful testing.</p>
<p>NOTE: Using <code>${user.dir}</code>, the log files will be created in the root of the project.  We will want to configure this differently for production.</p>
<div  style="font-size:smaller">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;configuration&gt;
  &lt;statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /&gt;

  &lt;filter class="ch.qos.logback.access.filter.CountingFilter"&gt;
    &lt;name&gt;countingFilter&lt;/name&gt;
  &lt;/filter&gt;

  &lt;appender name="accessfile" class="ch.qos.logback.core.rolling.RollingFileAppender"&gt;
    &lt;file&gt;${user.dir}/logs/app-access.log&lt;/file&gt;
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"&gt;
        &lt;fileNamePattern&gt;${user.dir}/logs/app-access.%d{yyyy-MM-dd}.log.zip&lt;/fileNamePattern&gt;
    &lt;/rollingPolicy&gt;

    &lt;encoder&gt;
        &lt;pattern&gt;combined&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;appender name="console" class="ch.qos.logback.core.ConsoleAppender"&gt;
    &lt;encoder&gt;
      &lt;pattern&gt;%n%fullRequest%n%fullResponse%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;appender name="reqrespfile" class="ch.qos.logback.core.rolling.RollingFileAppender"&gt;
    &lt;file&gt;${user.dir}/logs/app-req-resp.log&lt;/file&gt;
    &lt;rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"&gt;
      &lt;fileNamePattern&gt;${user.dir}/logs/app-req-resp.%d{yyyy-MM-dd}.log.zip&lt;/fileNamePattern&gt;
    &lt;/rollingPolicy&gt;

    &lt;encoder&gt;
      &lt;pattern&gt;%n%fullRequest%n%fullResponse%n&lt;/pattern&gt;
    &lt;/encoder&gt;
  &lt;/appender&gt;

  &lt;appender-ref ref="accessfile" /&gt;
  &lt;appender-ref ref="reqrespfile" /&gt;
  &lt;appender-ref ref="console" /&gt;
&lt;/configuration&gt;
</pre>
</div>
<p>See <a href="http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank">Enterprise Spring Best Practices &#8211; XML Configuration &#8211; Part 3</a> for Spring configuration of <code>java.util.logging</code> and <code>System.out</code>, <code>System.err</code> handlers for SLF4J. </p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="jetty">Running with Jetty and Tomcat</a></h2>
<hr/>
<!-- ******************************************** --><br />
Developers can run Jetty or Tomcat for testing with the following Maven plugin configuration. The plugin configuration below configures the servers for JMX, SLF4J, Logback and Logback Access.</p>
<div style="font-weight:bold">Running Jetty</div>
<pre>
    $ mvn clean install jetty:run
</pre>
<div style="font-weight:bold">Running Tomcat 7</div>
<pre>
    $ mvn clean install tomcat7:run
</pre>
<p style="font-size:125%;color:DarkRed">NOTE: DO NOT use <code>tomcat:run</code>, this is the old Tomcat plugin.</p>
<div  style="font-size:smaller">
<pre class="brush:xml">
&lt;properties&gt;
...
  &lt;maven.jetty.plugin&gt;8.1.10.v20130312&lt;/maven.jetty.plugin&gt;
...
  &lt;maven.tomcat.plugin&gt;2.1&lt;/maven.tomcat.plugin&gt;
...
&lt;/properties&gt;

...

&lt;plugins&gt;
...
  &lt;plugin&gt;
  &lt;groupId&gt;org.apache.tomcat.maven&lt;/groupId&gt;
  &lt;artifactId&gt;tomcat7-maven-plugin&lt;/artifactId&gt;
  &lt;version&gt;${maven.tomcat.plugin}&lt;/version&gt;
  &lt;configuration&gt;
    &lt;systemProperties&gt;
    &lt;com.sun.management.jmxremote&gt;true&lt;/com.sun.management.jmxremote&gt;
    &lt;com.sun.management.jmxremote.port&gt;8050&lt;/com.sun.management.jmxremote.port&gt;
    &lt;com.sun.management.jmxremote.ssl&gt;false&lt;/com.sun.management.jmxremote.ssl&gt;
    &lt;com.sun.management.jmxremote.authenticate&gt;false&lt;/com.sun.management.jmxremote.authenticate&gt;
    &lt;java.util.logging.manager&gt;org.apache.juli.ClassLoaderLogManager&lt;/java.util.logging.manager&gt;
    &lt;logback.ContextSelector&gt;JNDI&lt;/logback.ContextSelector&gt;
  &lt;/systemProperties&gt;
  &lt;/configuration&gt;
  &lt;dependencies&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
    &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
    &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
    &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt;
    &lt;version&gt;${slf4j.version}&lt;/version&gt;
    &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
    &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;dependency&gt;
    &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
    &lt;artifactId&gt;logback-access&lt;/artifactId&gt;
    &lt;version&gt;${logback.version}&lt;/version&gt;
    &lt;scope&gt;runtime&lt;/scope&gt;
  &lt;/dependency&gt;
  &lt;/dependencies&gt;
  &lt;/plugin&gt;
  &lt;plugin&gt;
    &lt;groupId&gt;org.mortbay.jetty&lt;/groupId&gt;
    &lt;artifactId&gt;jetty-maven-plugin&lt;/artifactId&gt;
    &lt;version&gt;${maven.jetty.plugin}&lt;/version&gt;
    &lt;configuration&gt;
      &lt;webAppConfig&gt;
        &lt;contextPath&gt;/${project.name}&lt;/contextPath&gt;
      &lt;/webAppConfig&gt;
      &lt;stopPort&gt;9966&lt;/stopPort&gt;
      &lt;stopKey&gt;shutterdown&lt;/stopKey&gt;
      &lt;requestLog implementation="ch.qos.logback.access.jetty.RequestLogImpl"&gt;
        &lt;fileName&gt;./src/main/resources/logback-access.xml&lt;/fileName&gt;
      &lt;/requestLog&gt;
      &lt;systemProperties&gt;
        &lt;systemProperty&gt;
          &lt;name&gt;logback.configurationFile&lt;/name&gt;
          &lt;value&gt;./src/main/resources/logback.xml&lt;/value&gt;
        &lt;/systemProperty&gt;
        &lt;systemProperty&gt;
          &lt;name&gt;com.sun.management.jmxremote&lt;/name&gt;
          &lt;value&gt;true&lt;/value&gt;
        &lt;/systemProperty&gt;
        &lt;systemProperty&gt;
          &lt;name&gt;com.sun.management.jmxremote.port&lt;/name&gt;
          &lt;value&gt;8050&lt;/value&gt;
        &lt;/systemProperty&gt;
        &lt;systemProperty&gt;
          &lt;name&gt;com.sun.management.jmxremote.ssl&lt;/name&gt;
          &lt;value&gt;false&lt;/value&gt;
        &lt;/systemProperty&gt;
        &lt;systemProperty&gt;
          &lt;name&gt;com.sun.management.jmxremote.authenticate&lt;/name&gt;
          &lt;value&gt;false&lt;/value&gt;
        &lt;/systemProperty&gt;
      &lt;/systemProperties&gt;
    &lt;/configuration&gt;
    &lt;dependencies&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
        &lt;artifactId&gt;jcl-over-slf4j&lt;/artifactId&gt;
        &lt;version&gt;${slf4j.version}&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
        &lt;artifactId&gt;slf4j-api&lt;/artifactId&gt;
        &lt;version&gt;${slf4j.version}&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
        &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt;
        &lt;version&gt;${slf4j.version}&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
        &lt;artifactId&gt;logback-classic&lt;/artifactId&gt;
        &lt;version&gt;${logback.version}&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;
      &lt;dependency&gt;
        &lt;groupId&gt;ch.qos.logback&lt;/groupId&gt;
        &lt;artifactId&gt;logback-access&lt;/artifactId&gt;
        &lt;version&gt;${logback.version}&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
      &lt;/dependency&gt;
    &lt;/dependencies&gt;
  &lt;/plugin&gt;
...
&lt;/plugins&gt;
</pre>
</div>
<div style="font-weight:bold">Logback <code>web.xml</code> Helpers</div>
<p>To see Logback status, optionally add the following Logback Status servlet.</p>
<div  style="font-size:smaller">
<pre class="brush:xml">
...
  &lt;servlet&gt;
    &lt;servlet-name&gt;ViewStatusMessages&lt;/servlet-name&gt;
    &lt;servlet-class&gt;ch.qos.logback.classic.ViewStatusMessagesServlet&lt;/servlet-class&gt;
  &lt;/servlet&gt;

  &lt;servlet-mapping&gt;
    &lt;servlet-name&gt;ViewStatusMessages&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/logbackStatus&lt;/url-pattern&gt;
  &lt;/servlet-mapping&gt;
...
</pre>
</div>
<p>To capture the <code>HTTPRequest</code> and <code>HTTPResponse</code> data use the Logback Tee Filter.</p>
<div  style="font-size:smaller">
<pre class="brush:xml">
...
  &lt;filter&gt;
    &lt;filter-name&gt;TeeFilter&lt;/filter-name&gt;
    &lt;filter-class&gt;ch.qos.logback.access.servlet.TeeFilter&lt;/filter-class&gt;
  &lt;/filter&gt;

  &lt;filter-mapping&gt;
    &lt;filter-name&gt;TeeFilter&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
  &lt;/filter-mapping&gt;
...
</pre>
</div>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="spring">Spring Configuration Files</a></h2>
<hr/>
<!-- ******************************************** --><br />
Be consistent with naming Spring xml configuration files.  Start all files with the same name such as <code>applicationConfig*.xml</code>.</p>
<p>For example: <code>applicationConfig-bootstrap.xml</code>, <code>applicationConfig-jpa.xml</code>, <code>applicationConfig-security.xml</code>, etc.</p>
<p>In the next blog, I will discuss Enterprise Spring configuration best practices.</p>
<div style="font-weight:bold">Config Directories</div>
<ul>
<li><code>src/main/resources/META-INF/spring</code> &#8211; Spring XML configuration directory</li>
<li><code>src/main/webapp/WEB-INF/spring</code> &#8211; Spring MVC configuration directory</li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="maven">Complete Maven Config</a></h2>
<hr/>
<!-- ******************************************** --><br />
The <a href="https://gist.github.com/3044729" target="_blank">Best Practices Maven Config file</a> is tuned for Spring application dependencies, reporting and plugin support.</p>
<p><a href="https://gist.github.com/3044729" target="_blank">Features of the Best Practices Maven Config file:</a></p>
<ul>
<li>All versions in properties section</li>
<li>Dependency Management section controls transitive dependencies</li>
<li>All plugins defined with versions in Plugin Management section</li>
<li>Enforcer plugin stops build for incompatible dependencies</li>
<li>Maven Site plugin configured for reporting, with common reporting plugins</li>
<li>Eclipse plugin uses new Eclipse brand Maven plugin, formerly Sonatype&#8217;s</li>
<li>Idea (IntelliJ) plugin, is obsolete &#8211; not included</li>
<li>Versions plugin to check for dependency and plugin updates</li>
</ul>
<p><a href="https://gist.github.com/3044729" target="_blank">BEST Practices Maven Config File</a></p>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="maventips">Valuable Maven Commands</a></h2>
<hr/>
<!-- ******************************************** --></p>
<div style="font-weight:bold">Display Dependency Updates</div>
<pre>
    $ mvn versions:display-dependency-updates
</pre>
<div style="font-weight:bold">Display Plugin Updates</div>
<pre>
    $ mvn versions:display-plugin-updates
</pre>
<div style="font-weight:bold">Display Dependency Tree</div>
<pre>
    $ mvn dependency:tree -Ddetail
</pre>
<div style="font-weight:bold">Display Dependency List</div>
<pre>
    $ mvn dependency:list
</pre>
<div style="font-weight:bold">Display Effective POM</div>
<pre>
    $ mvn help:effective-pom
</pre>
<div style="font-weight:bold">Display Project Settings</div>
<pre>
    $ mvn help:effective-settings
</pre>
<div style="font-weight:bold">Display System and Environment Variables</div>
<pre>
    $ mvn help:system
</pre>
<div style="font-weight:bold">Display Build Class Path</div>
<pre>
    $ mvn dependency:build-classpath
</pre>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="reading">Further Reading</a></h2>
<hr/>
<!-- ******************************************** --></p>
<ul>
<li><a href="http://gordondickens.com/wordpress/2012/07/08/enterprise-spring-best-practices-part-2-application-architecture/" target="_blank">Enterprise Spring Best Practices &#8211; Application Architecture &#8211; Part 2</a></li>
<li><a href="http://gordondickens.com/wordpress/2012/07/30/enterprise-spring-framework-best-practices-part-3-xml-config/" target="_blank">Enterprise Spring Best Practices &#8211; XML Configuration &#8211; Part 3</a></li>
<li><a href="https://github.com/gordonad/enterprise-spring-best-practices" target="_blank">Enterprise Spring Best Practices &#8211; Source Code</a></li>
<li><a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/" target="_blank">FREE Spring Framework PDF (848 pages)</a></li>
<li><a href="http://maven.apache.org/" target="_blank">Apache Maven</a></li>
<li><a href="http://www.slf4j.org/" target="_blank">SLF4J</a></li>
<li><a href="http://logback.qos.ch/reasonsToSwitch.html" target="_blank">Logback</a></li>
<li><a href="http://gradle.org/" target="_blank">Gradle</a></li>
</ul>
<p><!-- ******************************************** --><br />
<br/></p>
<h2><a name="social">Social Me</a></h2>
<hr/>
<!-- ******************************************** --><br />
<a href="http://twitter.com/gdickens" target="_blank">Twitter &#8211; twitter.com/gdickens</a><br />
<a href="http://linkedin.com/in/gordondickens" target="_blank">LinkedIn &#8211; linkedin.com/in/gordondickens</a><br />
<a href="http://github.com/gordonad" target="_blank">GitHub: github.com/gordonad</a><br />
<a href="mailto:gordon@gordondickens.com" target="_blank">gordon@gordondickens.com</a></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/07/03/enterprise-spring-best-practices-part-1-project-config/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Gemini Blueprint &#8211; Converting from Spring OSGi</title>
		<link>http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/</link>
		<comments>http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/#comments</comments>
		<pubDate>Wed, 13 Jun 2012 18:41:32 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Blueprint]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Gemini]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Virgo]]></category>
		<category><![CDATA[beans]]></category>
		<category><![CDATA[blueprint]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[gemini]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[virgo]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=1453</guid>
		<description><![CDATA[Eclipse Virgo OSGi Enthusiasts, like myself, can now switch from the Spring OSGi namespace to the Eclipse Gemini Blueprint namespaces for bundles. Maven Dependencies &#60;!-- Gemini Blueprint OSGi --&#62; &#60;properties&#62; &#60;gemini.blueprint.version&#62;1.0.0.RELEASE&#60;/gemini.blueprint.version&#62; &#60;/properties&#62; ... &#60;dependency&#62; &#60;groupId&#62;org.eclipse.gemini&#60;/groupId&#62; &#60;artifactId&#62;org.eclipse.gemini.blueprint.extender&#60;/artifactId&#62; &#60;version&#62;${gemini.blueprint.version}&#60;/version&#62; &#60;exclusions&#62; &#60;exclusion&#62; &#60;groupId&#62;org.springframework&#60;/groupId&#62; &#8230; <a href="http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Eclipse Virgo OSGi Enthusiasts, like myself, can now switch from the Spring OSGi namespace to the Eclipse Gemini Blueprint namespaces for bundles.</p>
<p><br/></p>
<h3>Maven Dependencies</h3>
<div  style="font-size:small">
<pre class="brush:xml">
&lt;!-- Gemini Blueprint OSGi --&gt;
&lt;properties&gt;
  &lt;gemini.blueprint.version&gt;1.0.0.RELEASE&lt;/gemini.blueprint.version&gt;
&lt;/properties&gt;
...

&lt;dependency&gt;
  &lt;groupId&gt;org.eclipse.gemini&lt;/groupId&gt;
  &lt;artifactId&gt;org.eclipse.gemini.blueprint.extender&lt;/artifactId&gt;
  &lt;version&gt;${gemini.blueprint.version}&lt;/version&gt;
  &lt;exclusions&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.beans&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.core&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.context&lt;/artifactId&gt;
    &lt;/exclusion&gt;
  &lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.eclipse.gemini.blueprint&lt;/groupId&gt;
  &lt;artifactId&gt;gemini-blueprint-mock&lt;/artifactId&gt;
  &lt;version&gt;${gemini.blueprint.version}&lt;/version&gt;
  &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.eclipse.gemini&lt;/groupId&gt;
  &lt;artifactId&gt;org.eclipse.gemini.blueprint.core&lt;/artifactId&gt;
  &lt;version&gt;${gemini.blueprint.version}&lt;/version&gt;
  &lt;exclusions&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.aop&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.beans&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.core&lt;/artifactId&gt;
    &lt;/exclusion&gt;
    &lt;exclusion&gt;
      &lt;groupId&gt;org.springframework&lt;/groupId&gt;
      &lt;artifactId&gt;org.springframework.context&lt;/artifactId&gt;
    &lt;/exclusion&gt;
  &lt;/exclusions&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
  &lt;groupId&gt;org.eclipse.gemini&lt;/groupId&gt;
  &lt;artifactId&gt;org.eclipse.gemini.blueprint.io&lt;/artifactId&gt;
  &lt;version&gt;${gemini.blueprint.version}&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div>
<p><br/></p>
<h3>Repositories</h3>
<div  style="font-size:small">
<pre class="brush:xml">
&lt;repository&gt;
  &lt;id&gt;com.springsource.repository.bundle.external&lt;/id&gt;
  &lt;name&gt;SpringSource Enterprise Bundle Repository - External Bundle Releases&lt;/name&gt;
  &lt;url&gt;http://repository.springsource.com/maven/bundles/external&lt;/url&gt;
&lt;/repository&gt;
</pre>
</div>
<p><br/></p>
<h3>Eclipse Gemini Blueprint Config</h3>
<table>
<tbody>
<tr>
<th>XML Tag</th>
<th>Attributes</th>
<th>Description</th>
</tr>
<tr>
<td>&lt;bean /&gt;</td>
<td>id, activation, depends-on, class, init-method, destroy-method, factory-method, factory-ref, scope</td>
<td>The type definition for a component. The bean&#8217;s attributes provide the characteristics for how to create the bean instance.  Constructor arguments and injected properties are specified via child &lt;argument&gt; and &lt;property&gt; elements</td>
</tr>
<tr>
<td>&lt;blueprint /&gt;</td>
<td>default-activation, default-timeout, default-availability, </td>
<td>The root element for a blueprint configuration file with two sections. The first section (contained within the &lt;type-converters&gt; element) identifies components that are used for converting values into different target types.  The type converters are optional. The second section contains component definitions. Components are &lt;bean&gt;, &lt;service&gt;, &lt;reference&gt;, and &lt;reference-list&gt; elements that identify the bundle components that will be managed by the blueprint service</td>
</tr>
<tr>
<td>&lt;description /&gt;</td>
<td>&nbsp;</td>
<td>A generic element type to allow documentation to be added to the blueprint configuration</td>
</tr>
<tr>
<td>&lt;compendium:cm-properties /&gt;</td>
<td>id, persistent-id, local-override, dynamic, init-lazy, init-timeout</td>
<td>Exposes the properties found in the Configuration Admin service under the given &lt;persistent-id&gt;</td>
</tr>
<tr>
<td>&lt;compendium:managed-properties /&gt;</td>
<td>persistent-id, autowire-on-update, update-method</td>
<td>Defines a bean based on the given class name and configuration, with properties autowired-by-name based on the configuration stored under the given &lt;persistent-id&gt;</td>
</tr>
<tr>
<td>&lt;compendium:managed-service-factory /&gt;</td>
<td>auto-export, autowire-on-update, context-class-loader, depends-on, factory-pid, interface, update-method</td>
<td>Defines a collection of beans based on the given class name, with properties &lt;autowired-by-name&gt; based on the configuration sets stored under the given factory &lt;persistent-id&gt;</td>
</tr>
<tr>
<td>&lt;ref /&gt;</td>
<td>component-id</td>
<td>Defines a required &lt;component-id&gt; for the reference component</td>
</tr>
<tr>
<td>&lt;reference /&gt;</td>
<td>id, activation, depends-on, interface, filter, component-name, availability</td>
<td>Defines the instances of a registered &lt;service&gt;, with a &lt;timeout&gt;. If the &lt;timeout&gt; is not specified, the &lt;default-timeout&gt; value is inherited from the encapsulating &lt;blueprint&gt; definition</td>
</tr>
<tr>
<td>&lt;reference-list /&gt;</td>
<td>id, activation, depends-on, interface, filter, component-name, availability, member-type</td>
<td>Builds in the characteristics of the &lt;service&gt; type to define characteristics of the &lt;reference-list&gt;.  This adds in the characteristics that only apply to collections of references via &lt;member-type&gt;. Subnodes can be &lt;description &gt;, &lt;compendium:cm-properties &gt;, &lt;compendium:managed-properties &gt;, &lt;compendium:managed-service-factory &gt;, &lt;reference-listener &gt;</td>
</tr>
<tr>
<td>&lt;reference-listener /&gt;</td>
<td>ref, bind-method, unbind-method</td>
<td>A definition of a listener that will watch for bind/unbind events associated with the &lt;service&gt; reference. The listener can be a &lt;ref&gt; to a &lt;bean&gt; or &lt;reference&gt; element, or an inline &lt;bean&gt; or &lt;reference&gt;</td>
</tr>
<tr>
<td>&lt;service /&gt;</td>
<td>id, activation, depends-on, interface, ref, auto-export, ranking</td>
<td>Defines the type for services exported by this blueprint bundle. Services are sourced by either a &lt;ref&gt; to a &lt;bean&gt; component or an &lt;inline&gt; bean component</td>
</tr>
<tr>
<td>&lt;type-converters /&gt;</td>
<td>&nbsp;</td>
<td>Defines a set of &lt;bean&gt;, &lt;ref&gt;, or &lt;reference&gt; elements that identify the type converter components</td>
</tr>
</tbody>
</table>
<hr/>
<h3>Examples</h3>
<div  style="font-size:small">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0
    http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
  default-activation="eager"&gt;

  &lt;!-- import the DataSource from OSGi --&gt;
  &lt;reference id="dataSource" interface="javax.sql.DataSource"/&gt;

  &lt;!-- export the directory bean to OSGi under the Directory interface --&gt;
  &lt;service ref="directory" interface="greenpages.Directory"/&gt;
&lt;/blueprint&gt;
</pre>
</div>
<p><br/></p>
<div  style="font-size:small">
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:compendium="http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium"
  xsi:schemaLocation="http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium

http://www.eclipse.org/gemini/blueprint/schema/blueprint-compendium/gemini-blueprint-compendium.xsd


http://www.osgi.org/xmlns/blueprint/v1.0.0

  http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
  default-activation="eager"&gt;

  &lt;compendium:cm-properties id="database.props"
    persistent-id="greenpages.db.config"/&gt;

  &lt;!-- Export the JDBC DataSource with the Service Name 'dataSource' --&gt;
  &lt;service ref="dataSource" interface="javax.sql.DataSource"/&gt;
&lt;/blueprint&gt;
</pre>
</div>
<p><br/></p>
<h3>Resources</h3>
<ul>
<li><a href="http://www.eclipse.org/gemini/blueprint/documentation/migration/">Blueprint Migration &#8211; note: Repository referenced in article is not useful</a></li>
<li><a href="https://github.com/gordonad/greenpages">My Code Samples</a></li>
<li><a href="http://www.eclipse.org/gemini/blueprint/">Gemini Blueprint</a></li>
<li><a href="http://www.eclipse.org/virgo/">Eclipse Virgo</a></li>
</ul>
<p><br/></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/06/13/gemini-blueprint-converting-from-spring-osgi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SpringSource Tool Suite FAQ</title>
		<link>http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/</link>
		<comments>http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/#comments</comments>
		<pubDate>Tue, 12 Jun 2012 14:54:22 +0000</pubDate>
		<dc:creator>Gordon</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[OSGi]]></category>
		<category><![CDATA[Roo]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Batch]]></category>
		<category><![CDATA[Spring Framework]]></category>
		<category><![CDATA[Spring Integration]]></category>
		<category><![CDATA[Spring Roo]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[AspectJ]]></category>
		<category><![CDATA[Aspects]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[EIP]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[Integration]]></category>
		<category><![CDATA[osgi]]></category>
		<category><![CDATA[Project]]></category>
		<category><![CDATA[roo]]></category>
		<category><![CDATA[SpringSource Tool Suite]]></category>
		<category><![CDATA[STS]]></category>
		<category><![CDATA[Templates]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[Visualization]]></category>
		<category><![CDATA[Wizards]]></category>

		<guid isPermaLink="false">http://gordondickens.com/wordpress/?p=220</guid>
		<description><![CDATA[Eclipse is one of the most popular IDEs for Java &#038; Spring application development. Spring has developed the Spring IDE plugin providing developers with Spring aware tooling for our projects. SpringSource Tool Suite = { &#160;&#160;&#160;Eclipse + SpringIDE + M2Eclipse &#8230; <a href="http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Eclipse is one of the most popular IDEs for Java &#038; Spring application development.  Spring has developed the Spring IDE plugin providing developers with Spring aware tooling for our projects.</p>
<p><code>SpringSource Tool Suite = {<br />
&nbsp;&nbsp;&nbsp;Eclipse + SpringIDE + M2Eclipse +<br />
&nbsp;&nbsp;&nbsp;GroovyEclipse + AJDT + EMF +  WTP + DTP,<br />
&nbsp;&nbsp;&nbsp;more...<br />
}<br />
</code><br />
<br/></p>
<h2>Why use STS/SpringIDE</h2>
<ul>
<li><strong>Bean Configuration Editor</strong> &#8211; Content Sensitive bean editing. Defining beans in XML will give you the names of the properties when entering property values in XML. Multitab editor with tabs for Namespaces and namespace specific content (JDBC, Integration, etc).</li>
<li><strong>Beans Graph / Dependency Graph</strong> &#8211; visualizer for Spring config files &#038; config sets</li>
<li><strong>Beans Cross Reference View</strong>  &#8211; show bean references across multiple config files</li>
<li><strong>Beans Quick Cross Reference</strong> &#8211; cross ref info on beans in open config file</li>
<li><strong>Beans Quick Outline</strong> &#8211; outline of beans &#038; properties in open config file</li>
<li><strong>Spring Beans Searching</strong> &#8211; by name, id, class, pointcut, etc.</li>
<li><strong>Spring Bean Validation</strong> &#8211; see: Preferences > Spring > Project Validators</li>
<li><strong>Spring MVC Request Mappings View</strong> &#8211; discovers all MVC annotations</li>
<li><strong>Java Editor Enhancements</strong> &#8211; Predefined shortcuts for Spring features, such as &#8220;POST&#8221; <ctrl>-<space> in a controller will provide a controller method signature.  Quick fixes for missing annotations, etc.</li>
<li><strong>Visualization</strong> &#8211; Graphical editors for Beans &#038; Bean relationships, Spring Web Flow, Spring Batch, Spring Integration &#038; Spring Aspects/AOP.  Not just for show but editable too!</li>
<li><strong>Spring Explorer</strong> &#8211; Ever wondered&#8230; where are my bean config files?  Switch to Spring Explorer view to see the beans for the project.</li>
</ul>
<p><br/></p>
<h2>First Things</h2>
<ul>
<li><strong>Download</strong> and install STS from <a href="http://www.springsource.com/developer/sts">springsource.com/developer/sts</a></li>
</ul>
<p>[or]</p>
<ul>
<li><strong>Existing Eclipse</strong> installation?  Download the Spring IDE bookmarks from <a href="http://dist.springsource.com/release/TOOLS/composite/e3.6/bookmarks.xml">http://dist.springsource.com/release/TOOLS/composite/e3.6/bookmarks.xml</a> Then, import the bookmarks file from Preferences > Install/Update > Available Update Sites.</li>
</ul>
<p><br/></p>
<h2>What else is in the Box?</h2>
<ul>
<li>Groovy/Grails Support</li>
<li>Spring OSGi (Dynamic Modules/Eclipse Blueprint) Support</li>
<li>Spring dm Server / Eclipse Virgo Support</li>
<li>Spring Roo Support</li>
<li>Gradle Support</li>
<li>tcServer &#038; Insight</li>
<li>JDBC Support</li>
<li>UML Diagramming</li>
</ul>
<h2>FAQ</h2>
<p><strong>Q: Spring features not showing up in my project, what do I do?</strong><br />
A: Right click on the project, under &#8220;Spring Tools&#8230;&#8221; click &#8220;Add Spring Project Nature&#8221;</p>
<p><strong>Q: Why does Spring Explorer not show any bean config (XML) files?</strong><br />
A: Right click on the project, select &#8220;Properties&#8221; &#8211; In the properties dialog, Spring > Beans Support &#8211; click the &#8220;Scan&#8230;&#8221; button.</p>
<p><strong>Q: I imported a project but the red exclamation is over the icon?</strong><br />
A: If it is a Maven project, Right click on the project > Maven > Enable Dependency Management</p>
<p><strong>Q: Why doesn&#8217;t Spring find my configuration files when I run my JUnit tests? </strong><br />
A: When using Maven, you need to run &#8220;process-resources&#8221; or &#8220;resources:resources&#8221;.  Open Preferences > Maven and in the field &#8220;Goals to Run when updating project configuration&#8221; should have one of these values.  Then right click on the project, choose Run As > Maven package [or] Maven Install</p>
<p><strong>Q: Which version of Maven is STS running?</strong><br />
A: Check in Preferences > Maven > Installations &#8211; Eclipse Helios &#038; Indigo will by default install an OLD version of Maven 3.0.  It is recommended that you install a current release (3.0.3 at the time of this writing) and Add that to the installation list.</p>
<p><strong>Q: How do I open the Maven pom file in XML mode instead of the GUI mode?</strong><br />
A: Preferences > Maven > POM Editor > check &#8220;Open XML page in the POM editor by default&#8221;</p>
<p><strong>Q: How do I set AOP visualization to recognize my Spring Aspects?</strong><br />
A: Preferences > Visualiser > Check &#8220;Spring AOP Provider&#8221; in the &#8220;Available Providers&#8221; box.</p>
<p><strong>Q: I do not write Aspects, why should I care about Aspect Visualization?</strong><br />
A: Even if you do not write your own aspects, Spring implements them via some annotations such as @Transactional</p>
<p><strong>Q: What does the Spring Tools > Enable Spring Aspects tooling do?</strong><br />
A: Enables advanced JDT features &#8211; see: <a href="http://wiki.eclipse.org/JDT_weaving_features">wiki.eclipse.org/JDT_weaving_features</a></p>
<p><strong>Q: What do the letters &#8220;S&#8221;, &#8220;M&#8221;, &#8220;Aj&#8221;, etc mean over my project, directory and files in Eclipse?</strong><br />
A: &#8220;S&#8221; &#8211; Spring, &#8220;M&#8221; &#8211; Maven. &#8220;AJ&#8221; &#8211; AspectJ, &#8220;J&#8221; &#8211; Java</p>
<p><strong>Q: What is the AOP Event Trace View?</strong><br />
A: This view shows what Spring is doing when build it&#8217;s internal AOP bean model.</p>
<p><br/></p>
<hr/>
<p class="facebook"><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/" target="_blank"><img src="http://gordondickens.com/wordpress/wp-content/plugins/add-to-facebook-plugin/facebook_share_icon.gif" alt="Share on Facebook" title="Share on Facebook" /></a><a href="http://www.facebook.com/share.php?u=http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/" target="_blank" title="Share on Facebook">Share on Facebook</a></p>]]></content:encoded>
			<wfw:commentRss>http://gordondickens.com/wordpress/2012/06/12/springsource_tool_suite_faq/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
