<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Baeldung</title>
	
	<link>http://www.baeldung.com</link>
	<description>Java, Spring and Web Development tutorials</description>
	<lastBuildDate>Sun, 19 May 2013 21:53:58 +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>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Baeldung" /><feedburner:info uri="baeldung" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>Baeldung</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Spring Maven Repository</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/U2K0I6iRa9c/spring-maven-repository</link>
		<comments>http://www.baeldung.com/spring-maven-repository#comments</comments>
		<pubDate>Sun, 19 May 2013 11:12:17 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[maven]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=2054</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fb2adc8fa901007e54"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Guide on how to set up Maven to use Spring Repositories - Release Candidates, Milestones and Snapshots - after the Spring infrastructure updates.]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fbecb2a1427e00e2fa"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2><strong>1. Overview</strong></h2>
<p>This article will show what Maven Repositories to use when using Spring artifacts in a project &#8211; see the full list of repositories on <a title="Available Repositories" href="https://github.com/SpringSource/spring-framework/wiki/SpringSource-repository-FAQ#what-repositories-are-available" target="_blank">the Spring wiki</a>. The previous Spring artifact management infrastructure was <em>maven.springframework.org</em> &#8211; this has now been <a title="Spring Infrastructure Updates" href="http://blog.springsource.org/2012/06/27/spring-project-infrastructure-updates/" target="_blank">deprecated </a>in favor of the more powerful <em>repo.springsource.org</em>.</p>
<h2><strong>2. <strong>Maven Repository for </strong>Releases </strong></h2>
<p>Spring publishes all their GA/Release artifacts to Maven Central, so if only releases are needed, there is no need to add any new repository into the pom. There is however a custom, <a title="RELEASE (generally available) versions" href="http://repo.springsource.org/release/" target="_blank">browsable</a> <strong>Maven repository available for Spring Releases</strong> as well, if for some reason Maven Central is not available:</p>
<pre class="brush: xml; gutter: true">&lt;repositories&gt;
    &lt;repository&gt;
        &lt;id&gt;repository.springsource.release&lt;/id&gt;
        &lt;name&gt;SpringSource GA Repository&lt;/name&gt;
        &lt;url&gt;http://repo.springsource.org/release&lt;/url&gt;
    &lt;/repository&gt;
&lt;/repositories&gt;</pre>
<p>The Spring artifact versioning rules are explained <a title="Spring Artifact Versioning" href="https://github.com/SpringSource/spring-framework/wiki/Downloading-Spring-artifacts#wiki-artifact_versioning" target="_blank">on the project wiki</a>.</p>
<p>Spring Milestones and Snapshots are not published directly to Maven Central, so these have their own specific Maven repos.</p>
<h2><strong>3. <strong>Maven Repository for </strong>Milestones and Release Candidates<br />
</strong></h2>
<p>For Spring Milestones and RCs, the following repository needs to be added to the pom:</p>
<pre class="brush: xml; gutter: true">&lt;repositories&gt;
    &lt;repository&gt;
        &lt;id&gt;repository.springsource.milestone&lt;/id&gt;
        &lt;name&gt;SpringSource Milestone Repository&lt;/name&gt;
        &lt;url&gt;http://repo.springsource.org/milestone&lt;/url&gt;
    &lt;/repository&gt;
&lt;/repositories&gt;</pre>
<p>One this repository has been defined, the project can start using the Spring <a title="M* (milestone) and RC (release candidate) versions" href="http://repo.springsource.org/milestone/" target="_blank">milestone dependencies</a>:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
    &lt;version&gt;4.0.0.M1&lt;/version&gt;
&lt;/dependency&gt;</pre>
<h2><strong><strong>4. </strong><strong><strong>Maven Repository for </strong></strong>Snapshots</strong></h2>
<p>Similar to milestones, Spring snapshots are hosted in a custom repository:</p>
<pre class="brush: xml; gutter: true">&lt;repositories&gt;
    &lt;repository&gt;
        &lt;id&gt;repository.springsource.snapshot&lt;/id&gt;
        &lt;name&gt;SpringSource Snapshot Repository&lt;/name&gt;
        &lt;url&gt;http://repo.springsource.org/snapshot&lt;/url&gt;
    &lt;/repository&gt;
&lt;/repositories&gt;</pre>
<p>Once the repository is enabled in the pom, the project can start the using Spring snapshots:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
    &lt;version&gt;3.3.0.BUILD-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>And even:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-core&lt;/artifactId&gt;
    &lt;version&gt;4.0.0.BUILD-SNAPSHOT&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>The snapshot Spring repositories can now also be <a title="Spring Snapshots" href="http://repo.springsource.org/snapshot/" target="_blank">browsed</a>.</p>
<h2><strong>5. Maven Repository for Spring OSGI</strong></h2>
<p>OSGI compatible Spring artifacts are maintained in the SpringSource <a title="Spring OSGI Repos" href="http://ebr.springsource.com/repository/app/faq" target="_blank">Enterprise Bundle Repository</a> &#8211; in short, EBR. These repositories contains valid OSGI bundles and libraries for the entire Spring Framework, as well as a complete set of dependencies for these libraries. For bundles:</p>
<pre class="brush: xml; gutter: true">&lt;repository&gt;
    &lt;id&gt;com.springsource.repository.bundles.release&lt;/id&gt; 
    &lt;name&gt;SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases&lt;/name&gt; 
    &lt;url&gt;http://repository.springsource.com/maven/bundles/release&lt;/url&gt; 
&lt;/repository&gt;

&lt;repository&gt; 
    &lt;id&gt;com.springsource.repository.bundles.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>
<p>And for OSGI compatible libraries:</p>
<pre class="brush: xml; gutter: true">&lt;repository&gt;
    &lt;id&gt;com.springsource.repository.libraries.release&lt;/id&gt;
    &lt;name&gt;SpringSource Enterprise Bundle Repository - SpringSource Library Releases&lt;/name&gt;
    &lt;url&gt;http://repository.springsource.com/maven/libraries/release&lt;/url&gt;
&lt;/repository&gt;
&lt;repository&gt;
    &lt;id&gt;com.springsource.repository.libraries.external&lt;/id&gt;
    &lt;name&gt;SpringSource Enterprise Bundle Repository - External Library Releases&lt;/name&gt;
    &lt;url&gt;http://repository.springsource.com/maven/libraries/external&lt;/url&gt;
&lt;/repository&gt;</pre>
<h2><strong>6. Conclusion</strong></h2>
<p>This article describes the practical information about setting up Spring specific Maven Repositories in the pom &#8211; in order to use Release Candidates, Milestones and Snapshots.</p>
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/U2K0I6iRa9c" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-maven-repository/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-maven-repository?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-maven-repository</feedburner:origLink></item>
		<item>
		<title>Spring DataIntegrityViolationException</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/x57M6g_qhIE/spring-dataIntegrityviolationexception</link>
		<comments>http://www.baeldung.com/spring-dataIntegrityviolationexception#comments</comments>
		<pubDate>Fri, 17 May 2013 08:17:13 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[exceptions]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[exception]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=2050</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fbecb2a1757f00e3c2"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Spring DataIntegrityViolationException - Causes and Solutions for Hibernate and JPA: ConstraintViolationException, PropertyValueException, DataException, EntityExistsException.]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fc2adc8fb001007e67"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2><strong>1. Overview</strong></h2>
<p>In this article, we will discuss the Spring <em><strong>org.springframework.dao.DataIntegrityViolationException</strong></em> – this is a generic data exception typically thrown by the Spring exception translation mechanism when dealing with lower level persistence exceptions. The article will discuss the most common causes of this exception along with the solution for each one.</p>
<h2><strong>2. <em>DataIntegrityViolationException</em> and Spring Exception Translation</strong></h2>
<p>The Spring exception translation mechanism can be applied transparently to all beans annotated with <em>@Repository</em> &#8211; by defining an exception translation bean post processor bean in the Context:</p>
<pre class="brush: xml; gutter: true">&lt;bean id=&quot;persistenceExceptionTranslationPostProcessor&quot; 
   class=&quot;org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor&quot; /&gt;</pre>
<p>Or in Java:</p>
<pre class="brush: java; gutter: true">@Configuration
public class PersistenceHibernateConfig{
   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
      return new PersistenceExceptionTranslationPostProcessor();
   }
}</pre>
<p>The Exception translation mechanism is also enabled by default on the older persistence template available in Spring &#8211; the HibernateTemplate, JpaTemplate, etc.</p>
<h2><strong>3. Where is <em>DataIntegrityViolationException</em> thrown</strong></h2>
<h4><strong>3.1. <em>DataIntegrityViolationException</em> with Hibernate</strong></h4>
<p>When Spring is configured with Hibernate, the <em>exception</em> is thrown in the exception translation layer provided by Spring &#8211; <em>SessionFactoryUtils &#8211; convertHibernateAccessException</em>.</p>
<p>There are three possible Hibernate exceptions that may cause the <em>DataIntegrityViolationException</em> to be thrown:</p>
<ul>
<li><em>org.hibernate.exception.ConstraintViolationException</em></li>
<li><em>org.hibernate.PropertyValueException</em></li>
<li><em>org.hibernate.exception.DataException</em></li>
</ul>
<h4><strong>3.2. <em>DataIntegrityViolationException</em> With JPA</strong></h4>
<p>When Spring is configured with JPA as its persistence provider, the <em>DataIntegrityViolationException</em> is thrown, similar to Hibernate, in the exception translation layer &#8211; namely in <em>EntityManagerFactoryUtils &#8211; convertJpaAccessExceptionIfPossible</em>.</p>
<p>There is a single JPA exception that may trigger a <em>DataIntegrityViolationException</em> to be thrown &#8211; the <em>javax.persistence.EntityExistsException</em>.</p>
<h2><strong>4. Cause: <em>org.hibernate.exception.ConstraintViolationException</em></strong></h2>
<p>This is by far the most common cause of <em>DataIntegrityViolationException</em> being thrown &#8211; the Hibernate <em>ConstraintViolationException</em> indicates that the operation has violated a database integrity constraint.</p>
<p>Consider the following example &#8211; for One to One mapping through an explicit foreign key column between a <em>Parent</em> and <em>Child</em> entities &#8211; the following operations should fail:</p>
<pre class="brush: java; gutter: true">@Test(expected = DataIntegrityViolationException.class)
public void whenChildIsDeletedWhileParentStillHasForeignKeyToIt_thenDataException() {
   Child childEntity = new Child();
   childService.create(childEntity);

   Parent parentEntity = new Parent(childEntity);
   service.create(parentEntity);

   childService.delete(childEntity);
}</pre>
<p>The <em>Parent</em> entity has a foreign key to the <em>Child</em> entity &#8211; so deleting the child would break the foreign key constraint on the Parent &#8211; which results in a <em>ConstraintViolationException</em> &#8211; wrapped by Spring in the <em>DataIntegrityViolationException</em>:</p>
<pre class="brush: bash; gutter: true">org.springframework.dao.DataIntegrityViolationException: 
could not execute statement; SQL [n/a]; constraint [null]; 
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at o.s.orm.h.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:138)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement</pre>
<p>To solve this, the <em>Parent</em> should be deleted first:</p>
<pre class="brush: java; gutter: true">@Test
public void whenChildIsDeletedAfterTheParent_thenNoExceptions() {
   Child childEntity = new Child();
   childService.create(childEntity);

   Parent parentEntity = new Parent(childEntity);
   service.create(parentEntity);

   service.delete(parentEntity);
   childService.delete(childEntity);
}</pre>
<h2><strong>5. Cause: <em>org.hibernate.PropertyValueException</em></strong></h2>
<p>This is one of the more common causes of the <em>DataIntegrityViolationException</em> &#8211; in Hibernate, this will come down to an entity being persisted with a problem. Either the entity has a null property which is defined with a <strong><em>not-null</em> constraint</strong>, or an association of the entity may reference an <strong>unsaved, transient instance</strong>.</p>
<p>For example, the following entity has a not-null <em>name</em> property -</p>
<pre class="brush: java; gutter: true">@Entity
public class Foo {
   ...

   @Column(nullable = false)
   private String name;

   ...
}</pre>
<p>If the following test tries to persist the entity with a null value for <em>name</em>:</p>
<pre class="brush: java; gutter: true">@Test(expected = DataIntegrityViolationException.class)
public void whenInvalidEntityIsCreated_thenDataException() {
   fooService.create(new Foo());
}</pre>
<p>A database integrigy constraint is violated, and so the <em>DataIntegrityViolationException</em> is thrown:</p>
<pre class="brush: bash; gutter: true">org.springframework.dao.DataIntegrityViolationException: 
not-null property references a null or transient value: 
org.baeldung.spring.persistence.model.Foo.name; 
nested exception is org.hibernate.PropertyValueException: 
not-null property references a null or transient value: 
org.baeldung.spring.persistence.model.Foo.name
	at o.s.orm.h.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:160)
...
Caused by: org.hibernate.PropertyValueException: 
not-null property references a null or transient value: 
org.baeldung.spring.persistence.model.Foo.name
	at o.h.e.i.Nullability.checkNullability(Nullability.java:103)
...</pre>
<h2><strong>6. Cause: <em>org.hibernate.exception.DataException</em></strong></h2>
<p>A Hibernate <em>DataException</em> indicates an invalid SQL Statement &#8211; something was wrong with the statement or the data, in that particular context. For example, using or <em>Foo</em> entity from before, the following would trigger this exception:</p>
<pre class="brush: java; gutter: true">@Test(expected = DataIntegrityViolationException.class)
public final void whenEntityWithLongNameIsCreated_thenDataException() {
   service.create(new Foo(randomAlphabetic(2048)));
}</pre>
<p>The actual exception for persisting the object with a long <em>name</em> value is:</p>
<pre class="brush: bash; gutter: true">org.springframework.dao.DataIntegrityViolationException: 
could not execute statement; SQL [n/a]; 
nested exception is org.hibernate.exception.DataException: could not execute statement
   at o.s.o.h.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:143)
...
Caused by: org.hibernate.exception.DataException: could not execute statement
	at o.h.e.i.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:71)</pre>
<p>In this particular example, the solution is to specify the max length of the name:</p>
<pre class="brush: java; gutter: true">@Column(nullable = false, length = 4096)</pre>
<h2><strong>7. Cause: <em>javax.persistence.EntityExistsException</em></strong></h2>
<p>Simillarly to Hibernate, the <em>EntityExistsException</em> JPA exception will also be wrapped by the Spring Exception Translation into a <em>DataIntegrityViolationException</em>. The only difference is that JPA itself is already high level which makes this JPA exception the only potential cause of data integrity violations.</p>
<h2><strong>8. Potentially <em>DataIntegrityViolationException</em></strong></h2>
<p>In some cases where the <em>DataIntegrityViolationException</em> may be expected, another exception may be thrown &#8211; one such case is if a JSR-303 validator, such as <em>hibernate-validator</em> 4 or 5 exists on the classpath.</p>
<p>In that case, if the following entity is persisted with a null value for <em>name</em>, it will <strong>no longer fail with a data integrity violation</strong> triggered by the persistence layer:</p>
<pre class="brush: java; gutter: true">@Entity
public class Foo {
    ...
    @Column(nullable = false)
    @NotNull
    private String name;

    ...
}</pre>
<p>This is because the execution won&#8217;t get to the persistence layer &#8211; it will fail before that with a <em>javax.validation.ConstraintViolationException</em>:</p>
<pre class="brush: bash; gutter: true">javax.validation.ConstraintViolationException: 
Validation failed for classes [org.baeldung.spring.persistence.model.Foo] 
during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[ ConstraintViolationImpl{
    interpolatedMessage=&#039;may not be null&#039;, propertyPath=name, 
    rootBeanClass=class org.baeldung.spring.persistence.model.Foo, 
    messageTemplate=&#039;{javax.validation.constraints.NotNull.message}&#039;}
]
    at o.h.c.b.BeanValidationEventListener.validate(BeanValidationEventListener.java:159)
    at o.h.c.b.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:94)</pre>
<h2><strong>9. Conclusions</strong></h2>
<p>At the end of this article, we should have a clear map to navigate the variety of causes and problems that may lead to a <em>DataIntegrityViolationException</em> in Spring, as well as a good grasp on how to fix all of these problems.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/x57M6g_qhIE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-dataIntegrityviolationexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-dataIntegrityviolationexception?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-dataintegrityviolationexception</feedburner:origLink></item>
		<item>
		<title>Spring @RequestMapping</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/GrXE7isR-Rw/spring-requestmapping</link>
		<comments>http://www.baeldung.com/spring-requestmapping#comments</comments>
		<pubDate>Thu, 16 May 2013 14:51:20 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=2037</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fcecb2a13164007e61"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Spring @RequestMapping - Basic Example, @RequestParam, @PathVariable, Header mapping]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fcecb2a13064007c2b"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2><strong>1. Overview</strong></h2>
<p>In this article, we will discuss one of the main annotations in <strong>Spring MVC &#8211; the <em>@RequestMapping</em></strong> &#8211; this is used to map web requests to Spring Controller methods.</p>
<p>Throughout the article, we will test each of the mappings showed via simple <em>curl</em> commands.</p>
<h2><strong>2. <em>@RequestMapping</em> Basic Example</strong></h2>
<p>Let&#8217;s start with a simple example &#8211; mapping an HTTP request to a method using some straightforward criteria.</p>
<h4><strong>2.1. <em>@RequestMapping</em> &#8211; by Path</strong></h4>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;)
@ResponseBody
public String getFoosBySimplePath() {
    return &quot;Get some Foos&quot;;
}</pre>
<p>To test out this mapping with a simple <em>curl</em> command, run:</p>
<pre class="brush: bash; gutter: true">curl -i http://localhost:8080/spring-mvc/foos</pre>
<h4><strong>2.2. <em>@RequestMapping</em> &#8211; the HTTP Method</strong></h4>
<p>By default, the HTTP method mapped by a <em>@RequestMapping</em> is GET &#8211; this can of course be changed &#8211; for example to map to a POST request:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, method = RequestMethod.POST)
@ResponseBody
public String postFoos() {
    return &quot;Post some Foos&quot;;
}</pre>
<p>To test the POST via a <em>curl</em> comamnd:</p>
<pre class="brush: bash; gutter: true">curl i -X POST http://localhost:8080/spring-mvc/foos</pre>
<h1><strong>3. <em>@RequestMapping</em> and HTTP Headers</strong></h1>
<h4><strong>3.1. <em>@RequestMapping</em> with the <em>headers</em> attribute</strong></h4>
<p>The mapping can be narrowed even further by specifying a header for the request:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, headers = &quot;key=val&quot;)
@ResponseBody
public String getFoosWithHeader() {
    return &quot;Get some Foos with Header&quot;;
}</pre>
<p>And even multiple headers via the <em>header</em> attribute of <em>@RequestMapping</em>:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, headers = { &quot;key1=val1&quot;, &quot;key2=val2&quot; })
@ResponseBody
public String getFoosWithHeaders() {
    return &quot;Get some Foos with Header&quot;;
}</pre>
<p>To test the operation, we&#8217;re going to use the <em>curl</em> header support:</p>
<pre class="brush: bash; gutter: true">curl -i -H &quot;key:val&quot; http://localhost:8080/spring-mvc/foos</pre>
<p>Note that for the <em>curl</em> syntax for separating the header key and the header value is a colon, same as in the HTTP spec, while in Spring the equals sign is used.</p>
<h4><strong>3.2. <em>@RequestMapping</em> Consumes and Produces</strong></h4>
<p>Mapping media types produced by a controller method is worth special attention &#8211; we can map a request based on its <em>Accept</em> header via the <em>@RequestMapping</em> headers attribute introduced above:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, method = RequestMethod.GET, headers = &quot;Accept=application/json&quot;)
@ResponseBody
public String getFoosAsJsonFromBrowser() {
    return &quot;Get some Foos with Header Old&quot;;
}</pre>
<p>The matching for this way of defining the <em>Accept</em> header is flexible &#8211; it uses contains instead of equals, so a request such as the following would still map correctly:</p>
<pre class="brush: bash; gutter: true">curl -H &quot;Accept:application/json,text/html&quot; http://localhost:8080/spring-mvc/foos</pre>
<p>Starting with Spring 3.1, a the <strong><em>@RequestMapping</em> annotation now has a <em>produces</em> and a <em>consumes</em> attributes</strong>, specifically for this purpose:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, method = RequestMethod.GET, produces = &quot;application/json&quot;)
@ResponseBody
public String getFoosAsJsonFromREST() {
    return &quot;Get some Foos with Header New&quot;;
}</pre>
<p>Also, the old type of mapping with the <em>headers</em> attribute will automatically be converted to the new <em>produces</em> mechanism starting with Spring 3.1, so the results will be identical.</p>
<p>This is consumed via <em>curl</em> in the same way:</p>
<pre class="brush: bash; gutter: true">curl -H &quot;Accept:application/json&quot; http://localhost:8080/spring-mvc/foos</pre>
<p>Additionally, <em>produces</em> support multiple values as well:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos&quot;, produces = { &quot;application/json&quot;, &quot;application/xml&quot; })</pre>
<p>Keep in mind that these are basically the same mapping, so Spring won&#8217;t accept them together &#8211; having both these methods active would result in:</p>
<pre class="brush: bash; gutter: true">Caused by: java.lang.IllegalStateException: Ambiguous mapping found. 
Cannot map &#039;fooController&#039; bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromREST()
to {[/foos],methods=[GET],params=[],headers=[],consumes=[],produces=[application/json],custom=[]}: 
There is already &#039;fooController&#039; bean method
public java.lang.String org.baeldung.spring.web.controller.FooController.getFoosAsJsonFromBrowser() 
mapped.</pre>
<p>A final note on the new <em>produces</em> and <em>consumes</em> mechanism &#8211; these behave differently from most other annotations: when specified at type level, <strong>the method level annotations do not complement but override</strong> the type level information.</p>
<h2><strong>4. <em>@RequestMapping</em> with Path Variables</strong></h2>
<p>Parts of the mapping URI can be bound to variables via the <em>@PathVariable</em> annotation.</p>
<h4><strong>4.1. Single <em>@PathVariable</em></strong></h4>
<p>A simple example with a single path variable:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos/{id}&quot;)
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable(&quot;id&quot;) long id) {
   return &quot;Get a specific Foo with id=&quot; + id;
}</pre>
<p>This can be tested with <em>curl</em>:</p>
<pre class="brush: bash; gutter: true">curl http://localhost:8080/spring-mvc/foos/1</pre>
<p>If the name of the method argument matches the name of the path variable exactly, then this can be simplified by <strong>using <em>@PathVariable</em> with no value</strong>:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos/{id}&quot;)
@ResponseBody
public String getFoosBySimplePathWithPathVariable(@PathVariable String id) {
   return &quot;Get a specific Foo with id=&quot; + id;
}</pre>
<p>Note that <em>@PathVariable</em> benefits from automatic type conversion, so we could have also declared the id as:</p>
<pre class="brush: java; gutter: true">@PathVariable long id</pre>
<h4><strong>4.2. Multiple <em>@PathVariable</em></strong></h4>
<p>More complex URI may need to map multiple parts of the URI to <strong>multiple values</strong>:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos/{fooid}/bar/{barid}&quot;)
@ResponseBody
public String getFoosBySimplePathWithPathVariables(@PathVariable long fooid, @PathVariable long barid) {
    return &quot;Get a specific Bar with id=&quot; + barid + &quot; from a Foo with id=&quot; + fooid;
}</pre>
<p>This is easily tested with <em>curl</em> in the same way:</p>
<pre class="brush: bash; gutter: true">curl http://localhost:8080/spring-mvc/foos/1/bar/2</pre>
<h4><strong>4.3. <strong><em>@PathVariable</em></strong> with RegEx</strong></h4>
<p>Regular expressions can also be used when mapping the <em>@PathVariable</em>; for example, we will restrict the mapping to only accept numerical values for the <em>id</em>:</p>
<pre class="brush: actionscript3; gutter: true">@RequestMapping(value = &quot;/bars/{numericId:[\\d]+}&quot;)
@ResponseBody
public String getBarsBySimplePathWithPathVariable(@PathVariable final long numericId) {
    return &quot;Get a specific Bar with id=&quot; + numericId;
}</pre>
<p>This will mean that the following URIs will match:</p>
<pre class="brush: bash; gutter: true">http://localhost:8080/spring-mvc/bars/1</pre>
<p>But this will not:</p>
<pre class="brush: bash; gutter: true">http://localhost:8080/spring-mvc/bars/abc</pre>
<h2><strong>5. <em>@RequestMapping</em> with Request Parameters</strong></h2>
<p>@RequestMapping allows easy <strong>mapping of URL parameters with the <em>@RequestParam</em> annotation</strong>. <strong><em><br />
</em></strong></p>
<p>We are now mapping a request to an URI such as:</p>
<pre class="brush: bash; gutter: true">http://localhost:8080/spring-mvc/bars?id=100</pre>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/bars&quot;)
@ResponseBody
public String getBarBySimplePathWithRequestParam(@RequestParam(&quot;id&quot;) long id) {
    return &quot;Get a specific Bar with id=&quot; + id;
}</pre>
<p>We are then extracting the value of the <em>id</em> parameter using the <em>@RequestParam(&#8220;id&#8221;)</em> annotation in the controller method signature.</p>
<p>The send a request with the id parameter, we&#8217;ll use the parameter support in <em>curl</em>:</p>
<pre class="brush: bash; gutter: true">curl -i -X POST id=100 http://localhost:8080/spring-mvc/bars</pre>
<p>In this example, the parameter was bound directly without having been declared first.</p>
<p>For more advanced scenarios, <strong><em>@RequestMapping</em> can explicitly define the parameters</strong> to be mapped as yet another way of narrowing the request mapping:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/bars&quot;, params = &quot;id&quot;)
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParam(@RequestParam(&quot;id&quot;) long id) {
    return &quot;Get a specific Bar with id=&quot; + id;
}</pre>
<p>Even more flexible mappings are allowed &#8211; multiple <em>params</em> values can be defined, and not all of them have to be used:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/bars&quot;, params = { &quot;id&quot;, &quot;second&quot; })
@ResponseBody
public String getBarBySimplePathWithExplicitRequestParams(@RequestParam(&quot;id&quot;) long id) {
    return &quot;Narrow Get a specific Bar with id=&quot; + id;
}</pre>
<p>And of course, a request to an URI such as:</p>
<pre class="brush: bash; gutter: true">http://localhost:8080/spring-mvc/bars?id=100&amp;second=something</pre>
<p>Will always be mapped to the best match &#8211; which is the narrower match, which defines both the <em>id</em> and the <em>second</em> parameter.</p>
<h2><strong>6. <em>@RequestMapping</em> Corner Cases</strong></h2>
<h4><strong>6.1. <em>@RequestMapping</em> &#8211; multiple paths mapped to the same controller method</strong></h4>
<p>Although a single <em>@RequestMapping</em> path value is usually used for a single controller method, this is just good practice, not a hard and fast rule &#8211; there are some cases where mapping multiple requests to the same method may be necessary. For that case, <strong>the <em>value</em> attribute of <em>@RequestMapping</em><em></em> does accept multiple mappings</strong>, not just a single one:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = { &quot;/advanced/bars&quot;, &quot;/advanced/foos&quot; })
@ResponseBody
public String getFoosOrBarsByPath() {
    return &quot;Advanced - Get some Foos or Bars&quot;;
}</pre>
<p>Now, both of these curl commands should hit the same method:</p>
<pre class="brush: bash; gutter: true">curl -i http://localhost:8080/spring-mvc/advanced/foos
curl -i http://localhost:8080/spring-mvc/advanced/bars</pre>
<h4><strong>6.2. <em>@RequestMapping</em> &#8211; multiple HTTP request methods to the same controller method</strong></h4>
<p>Multiple requests using different HTTP verbs can be mapped to the same controller method:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;/foos/multiple&quot;, method = { RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public String putAndPostFoos() {
    return &quot;Advanced - PUT and POST within single method&quot;;
}</pre>
<p>With <em>curl</em>, both of these will now hit the same method:</p>
<pre class="brush: bash; gutter: true">curl -i -X POST http://localhost:8080/spring-mvc/foos/multiple
curl -i -X PUT http://localhost:8080/spring-mvc/foos/multiple</pre>
<h4><strong>6.3. <em>@RequestMapping</em> &#8211; a fallback for all requests</strong></h4>
<p>To implement a simple fallback for all requests using a specific HTTP method:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;*&quot;)
@ResponseBody
public String getFallback() {
    return &quot;Fallback for GET Requests&quot;;
}</pre>
<p>Or even for all request:</p>
<pre class="brush: java; gutter: true">@RequestMapping(value = &quot;*&quot;, method = { RequestMethod.GET, RequestMethod.POST ... })
@ResponseBody
public String allFallback() {
    return &quot;Fallback for All Requests&quot;;
}</pre>
<h2><strong>7. Spring Configuration</strong></h2>
<p>The Spring MVC Configuration is simple enough &#8211; considering that our FooController is defined in the following package:</p>
<pre class="brush: java; gutter: true">package org.baeldung.spring.web.controller;

@Controller
public class FooController { ... }</pre>
<p>Starting with Spring 3.1, we will only need a <em>@Configuration</em> class to enable the full MVC support and configure classpath scanning for the controller:</p>
<pre class="brush: java; gutter: true">@Configuration
@EnableWebMvc
@ComponentScan({ &quot;org.baeldung.spring.web.controller&quot; })
public class MvcConfig {
    //
}</pre>
<h2><strong>8. Conclusion</strong></h2>
<p>This article focus on the <strong><em>@RequestMapping</em> annotation in Spring 3 </strong>- discussing a simple usecase, the mapping of HTTP headers, binding parts of the URI with <em>@PathVariable</em> and working with URI parameters and the <em>@RequestParam</em> annotation.</p>
<p>The implementation of this simple project can be found in <a title="Spring MVC Project on Github" href="https://github.com/eugenp/tutorials/tree/master/spring-mvc" target="_blank">the github project</a> – this is an Eclipse based project, so it should be easy to import and run as it is.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/GrXE7isR-Rw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-requestmapping/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-requestmapping?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-requestmapping</feedburner:origLink></item>
		<item>
		<title>Hibernate 4 with Spring</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/cIctNUQwl30/hibernate-4-spring</link>
		<comments>http://www.baeldung.com/hibernate-4-spring#comments</comments>
		<pubDate>Mon, 13 May 2013 12:09:22 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1969</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fc2adc8fc101007ce8"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Hibernate 4 with Spring]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fd2adc8faa01007d25"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2 id="overview"><strong>1. Overview</strong></h2>
<p>This article will focus on setting up <strong>Hibernate 4 with Spring</strong> – we’ll look at how to setup and configure Spring 3 with Hibernate 4 using both Java and XML Configuration. Parts of this process are common to Hibernate 3, and have been discussed previously on the <a title="Hibernate 3 with Spring" href="http://www.baeldung.com/hibernate3-spring">Hibernate 3 with Spring</a> article.</p>
<h2 id="maven"><strong>2. Maven</strong></h2>
<p>To add the Spring Persistence dependencies to the pom, please see the <a title="Spring with Maven - Persistence" href="http://www.baeldung.com/spring-with-maven#persistence">Spring with Maven article</a>.</p>
<p>Continuing with Hibernate 4, the Maven dependencies are simple:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
   &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
   &lt;version&gt;4.2.1.Final&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>Then, to enable Hibernate to use its proxy model, we need javassist as well:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;org.javassist&lt;/groupId&gt;
   &lt;artifactId&gt;javassist&lt;/artifactId&gt;
   &lt;version&gt;3.17.1-GA&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>And since we&#8217;re going to use MySQL for this tutorial, we&#8217;ll also need:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;mysql&lt;/groupId&gt;
   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
   &lt;version&gt;5.1.25&lt;/version&gt;
   &lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;</pre>
<h2 id="java_config"><strong>3. Java </strong><strong>Spring Configuration for Hibernate 4</strong></h2>
<p>To use <strong>Hibernate 4 in a project</strong>, a few things have changed on the configuration side when moving from a Hibernate 3 setup.</p>
<p>The main aspect that is different when upgrading from Hibernate 3 is the way to create the <strong><em>SessionFactory</em> with Hibernate 4</strong>.</p>
<p>This is now done by using the <em>LocalSessionFactoryBean</em> from the <em><strong>hibernate4</strong></em> package &#8211; which replaces the older <em><strong>AnnotationSessionFactoryBean</strong></em> from the <em><strong>hibernate3</strong></em> package. The new <em>FactoryBean</em> has the same responsibility &#8211; it bootstraps the <em>SessionFactory</em> from annotation scanning. This is neccessary because, starting with Hibernate 3.6, the old <em>AnnotationConfiguration</em> <a title="Merge AnnotationConfiguration into Configuration" href="https://hibernate.atlassian.net/browse/HHH-5375" target="_blank">was merged</a> into <em>Configuration</em> and so the new Hibernate 4 <em>LocalSessionFactoryBean</em> is using this new <em>Configuration</em> mechanism.</p>
<div class="woo-sc-box info medium rounded full" style="padding-left:15px;background-image:none;">
<p>It is also worth noting that, in Hibernate 4, the <em>Configuration.buildSessionFactory</em> method and mechanism <a title="JIRA - Revist passing of ServiceRegistry to Configuration to build a SessionFactory" href="https://hibernate.atlassian.net/browse/HHH-5991" target="_blank">have also been deprecated</a> <a title="SO -  Is buildSessionFactory() deprecated in hibernate 4?" href="http://stackoverflow.com/questions/8621906/is-buildsessionfactory-deprecated-in-hibernate-4" target="_blank">in favour</a> of <em>Configuration.buildSessionFactory(ServiceRegistry)</em> &#8211; which the Spring <em>LocalSessionFactoryBean</em> is not yet using.</p>
</div>
<p>The Spring Java Configuration for Hibernate 4:</p>
<pre class="brush: java; gutter: true">import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;

@Configuration
@EnableTransactionManagement
@PropertySource({ &quot;classpath:persistence-mysql.properties&quot; })
@ComponentScan({ &quot;org.baeldung.spring.persistence&quot; })
public class PersistenceConfig {

   @Autowired
   private Environment env;

   @Bean
   public LocalSessionFactoryBean sessionFactory() {
      LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { &quot;org.baeldung.spring.persistence.model&quot; });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(env.getProperty(&quot;jdbc.driverClassName&quot;));
      dataSource.setUrl(env.getProperty(&quot;jdbc.url&quot;));
      dataSource.setUsername(env.getProperty(&quot;jdbc.user&quot;));
      dataSource.setPassword(env.getProperty(&quot;jdbc.pass&quot;));

      return dataSource;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());

      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         {
            setProperty(&quot;hibernate.hbm2ddl.auto&quot;, env.getProperty(&quot;hibernate.hbm2ddl.auto&quot;));
            setProperty(&quot;hibernate.dialect&quot;, env.getProperty(&quot;hibernate.dialect&quot;));
         }
      };
   }
}</pre>
<h2 id="xml_config"><strong>4. XML Spring Configuration for Hibernate 4<br />
</strong></h2>
<p>Simillary, <strong>Hibernate 4 can be configured with XML</strong> as well:</p>

<pre class="brush: xml; gutter: true">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; 
   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; 
   xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
   xsi:schemaLocation=&quot;
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd&quot;&gt;

   &lt;context:property-placeholder location=&quot;classpath:persistence-mysql.properties&quot; /&gt;

   &lt;bean id=&quot;sessionFactory&quot; 
    class=&quot;org.springframework.orm.hibernate4.LocalSessionFactoryBean&quot;&gt;
      &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;
      &lt;property name=&quot;packagesToScan&quot; value=&quot;org.baeldung.spring.persistence.model&quot; /&gt;
      &lt;property name=&quot;hibernateProperties&quot;&gt;
         &lt;props&gt;
            &lt;prop key=&quot;hibernate.hbm2ddl.auto&quot;&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;
            &lt;prop key=&quot;hibernate.dialect&quot;&gt;${hibernate.dialect}&lt;/prop&gt;
         &lt;/props&gt;
      &lt;/property&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;dataSource&quot; 
    class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
      &lt;property name=&quot;driverClassName&quot; value=&quot;${jdbc.driverClassName}&quot; /&gt;
      &lt;property name=&quot;url&quot; value=&quot;${jdbc.url}&quot; /&gt;
      &lt;property name=&quot;username&quot; value=&quot;${jdbc.user}&quot; /&gt;
      &lt;property name=&quot;password&quot; value=&quot;${jdbc.pass}&quot; /&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;txManager&quot; 
    class=&quot;org.springframework.orm.hibernate4.HibernateTransactionManager&quot;&gt;
      &lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot; /&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;persistenceExceptionTranslationPostProcessor&quot; 
    class=&quot;org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor&quot;/&gt;

&lt;/beans&gt;</pre>

<p>To bootstrap the XML into the Spring Context, we can use a simple Java Configuration file if the application is configured with Java configuration:</p>
<pre class="brush: java; gutter: true">@Configuration
@EnableTransactionManagement
@ImportResource({ &quot;classpath:hibernate4Config.xml&quot; })
public class HibernateXmlConfig{
   //
}</pre>
<p>Alternativelly we can simply provide the XML file to the Spring Context, if the overall configuration is purely XML.</p>
<p>For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file:</p>
<pre class="brush: shell; gutter: true"># jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql

# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop</pre>
<h2 id="mysql"><strong>5. Spring, Hibernate and MySQL</strong></h2>
<p>The Drivers and Dialects supported by Hibernate <a title="Hibernate and MySQL" href="www.baeldung.com/hibernate3-spring#mysql" target="_blank">have been extensively discussed</a> for Hibernate 3 &#8211; and everything still applies for Hibernate 4 as well.</p>
<h2 id="usage"><strong>6. Usage</strong></h2>
<p>At this point, Hibernate 4 is fully configured with Spring and we can<strong> inject the raw Hibernate</strong> <em>SessionFactory</em> directly whenever we need to:</p>
<pre class="brush: java; gutter: true">public abstract class BarHibernateDAO{

   @Autowired
   SessionFactory sessionFactory;

   ...

   protected Session getCurrentSession(){
      return sessionFactory.getCurrentSession();
   }
}</pre>
<h2 id="conclusion"><strong>7. Conclusion</strong></h2>
<p>In this example, <strong>we configured Spring with Hiberate 4</strong> – both with Java and XML configuration. The implementation of this simple project can be found in <a title="Spring with Hibernate 4 Project on Github" href="https://github.com/eugenp/tutorials/tree/master/spring-hibernate4" target="_blank">the github project</a> – this is an Eclipse based project, so it should be easy to import and run as it is.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/cIctNUQwl30" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/hibernate-4-spring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/hibernate-4-spring?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=hibernate-4-with-spring</feedburner:origLink></item>
		<item>
		<title>Spring BeanDefinitionStoreException</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/6UukbKirJ6w/spring-beandefinitionstoreexception</link>
		<comments>http://www.baeldung.com/spring-beandefinitionstoreexception#comments</comments>
		<pubDate>Sat, 11 May 2013 20:11:45 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[exceptions]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[exception]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1999</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fdecb2a1147e00e3d6"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Spring BeanDefinitionStoreException - Causes, Solutions, IOException, FileNotFoundException]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fdecb2a13164007e62"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2 id="overview"><strong>1. Overview</strong></h2>
<p>In this article, we will discuss the Spring <em><strong>org.springframework.beans.factory.BeanDefinitionStoreException</strong></em> &#8211; this is typically the responsibility of a <em>BeanFactory</em> when a bean definition is invalid, the loading of that bean is problematic. The article will discuss the most common causes of this exception along with the solution for each one.</p>
<h2 id="filenotfound"><strong>2. Cause: <em>java.io.FileNotFoundException</em></strong></h2>
<h3><strong>2.1. <em>IOException</em> parsing XML document from ServletContext resource</strong></h3>
<p>This usually happens in a Spring Web application, when a <em>DispatcherServlet</em> is set up in the <em>web.xml</em> for Spring MVC:</p>
<pre class="brush: xml; gutter: true">&lt;servlet&gt;  
   &lt;servlet-name&gt;mvc&lt;/servlet-name&gt;  
   &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;  
&lt;/servlet&gt;</pre>
<p>By default, Spring will look for a file called exactly <em>springMvcServlet-servlet.xml</em> in the <em>/WEB-INF</em> directory of the web application.</p>
<p>If this file doesn&#8217;t exist, then the following exception will be thrown:</p>
<pre class="brush: bash; gutter: true">org.springframework.beans.factory.BeanDefinitionStoreException: 
IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-servlet.xml]; 
nested exception is java.io.FileNotFoundException: 
Could not open ServletContext resource [/WEB-INF/mvc-servlet.xml]</pre>
<p>The <strong>solution</strong> is of course to make sure the <em>mvc-servlet.xml</em> file indeed exists under <em>/WEB-INF</em>; if it doesn&#8217;t, then a sample one can be created:</p>

<pre class="brush: xml; gutter: true">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans 
   xmlns=&quot;http://www.springframework.org/schema/beans&quot;
   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
   xsi:schemaLocation=&quot;
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd&quot; &gt;

&lt;/beans&gt;</pre>

<h3><strong>2.2. <em>IOException</em> parsing XML document from class path resource</strong></h3>
<p>This usually happens when something in the application points to an XML resource that doesn&#8217;t exist, or is not placed where it should be.</p>
<p>Pointing to such a resource may happen in a variety of ways.</p>
<p>Using for example Java Configuration, this may look like:</p>
<pre class="brush: java; gutter: true">@Configuration
@ImportResource(&quot;beans.xml&quot;)
public class SpringConfig {...}</pre>
<p>In XML, this will be:</p>
<pre class="brush: xml; gutter: true">&lt;import resource=&quot;beans.xml&quot;/&gt;</pre>
<p>Or even by creating an Spring XML context manually:</p>
<pre class="brush: java; gutter: true">ApplicationContext context = new ClassPathXmlApplicationContext(&quot;beans.xml&quot;);</pre>
<p>All of these will leads to the same exception if the file doesn&#8217;t exist:</p>
<pre class="brush: bash; gutter: true">org.springframework.beans.factory.BeanDefinitionStoreException: 
IOException parsing XML document from ServletContext resource [/beans.xml]; 
nested exception is java.io.FileNotFoundException: 
Could not open ServletContext resource [/beans.xml]</pre>
<p>The <strong>solution</strong> is create the file and to place it under the <em>/src/main/resources</em> directory of the project &#8211; this way, the file will exist on the classpath and it will be found and used by Spring.</p>
<h2 id="properties"><strong>3. Cause: <em>Could not resolve placeholder &#8230;</em><br />
</strong></h2>
<p>This error occurs when Spring tries to resolve a property but is not able to &#8211; for one of many possible reasons.</p>
<p>But first, the usage of the property &#8211; this may be used in XML:</p>
<pre class="brush: xml; gutter: true">... value=&quot;${some.property}&quot; ...</pre>
<p>The property could also be used in Java code:</p>
<pre class="brush: java; gutter: true">@Value(&quot;${some.property}&quot;)
private String someProperty</pre>
<p>First thing to check is that the name of the property actually matches the property definition; in this example, we need to have the following property defined:</p>
<pre class="brush: bash; gutter: true">some.property=someValue</pre>
<p>Then, we need to check where the properties file is defined in Spring &#8211; this is described in detail in my <a title="Properties with Spring" href="http://www.baeldung.com/2012/02/06/properties-with-spring/">Properties with Spring</a> article. A good best practice to follow is to have all properties files under the <em>/src/main/resources</em> directory of the application and to load them up via:</p>
<pre class="brush: java; gutter: true">&quot;classpath:app.properties&quot;</pre>
<p>Moving on from the obvious &#8211; another possible cause that Spring is not able to resolve the property is that there may be <strong>multiple <em>PropertyPlaceholderConfigurer</em> beans</strong> in the Spring context (or multiple <em>property-placeholder</em> elements)</p>
<p>If that is the case, then the <strong>solution</strong> is either collapsing these into a single one, or configuring the one in the parent context with <em>ignoreUnresolvablePlaceholders</em>.</p>
<h2 id="nosuchmethoderror"><strong>4. Cause: <em>java.lang.NoSuchMethodError</em><br />
</strong></h2>
<p>This error comes in a variety of forms &#8211; one of the more common ones is:</p>
<pre class="brush: bash; gutter: true">org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/mvc-servlet.xml];
nested exception is java.lang.NoSuchMethodError:
org.springframework.beans.MutablePropertyValues.add (Ljava/lang/String;Ljava/lang/Object;)
Lorg/springframework/beans/MutablePropertyValues;</pre>
<p>This usually happens when there are multiple versions of Spring on the classpath. Having an <strong>older version of Spring accidentally on the project classpath</strong> is more common than one would think &#8211; I described the problem and the solution for this in the <a title="Spring Security with older Spring Core dependencies" href="www.baeldung.com/spring-security-with-maven#maven_problem">Spring Security with Maven</a> article.</p>
<p>In short, the solution for this error is simple &#8211; check all the Spring jars on the classpath and make sure that they all have the same version &#8211; and that version is 3.0 or above.</p>
<p>Simillarly, the exception is not restricted to the <em>MutablePropertyValues</em> bean &#8211; there are several other incarnations of the same problem, caused by the same version inconsistency:</p>
<pre class="brush: bash; gutter: true">org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from class path resource [/WEB-INF/mvc-servlet.xml];
- nested exception is java.lang.NoSuchMethodError:
org.springframework.util.ReflectionUtils.makeAccessible(Ljava/lang/reflect/Constructor;)V</pre>
<h2 id="noclassdeffounderror"><strong>5. Cause: <em>java.lang.NoClassDefFoundError</em><br />
</strong></h2>
<p>A common problem, simillarly related to Maven and the existing Spring dependencies is:</p>
<pre class="brush: bash; gutter: true">org.springframework.beans.factory.BeanDefinitionStoreException:
Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/mvc-servlet.xml];
nested exception is java.lang.NoClassDefFoundError: 
org/springframework/transaction/interceptor/TransactionInterceptor</pre>
<p>This occurs when transactional functionality is configured in the XML configuration:</p>
<pre class="brush: xml; gutter: true">&lt;tx:annotation-driven/&gt;</pre>
<p>The <em>NoClassDefFoundError</em> means that the Spring Transactional support &#8211; namely spring-tx &#8211; does not exist on the classpath.</p>
<p>The solution is simple &#8211; <em>spring-tx</em> needs to be defined in the Maven pom:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-tx&lt;/artifactId&gt;
    &lt;version&gt;3.2.2.RELEASE&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>Of course this is not limited to the transaction functionality &#8211; a similar error is thrown if AOP is missing as well:</p>
<pre class="brush: bash; gutter: true">Exception in thread &quot;main&quot; org.springframework.beans.factory.BeanDefinitionStoreException: 
Unexpected exception parsing XML document from class path resource [/WEB-INF/mvc-servlet.xml]; 
nested exception is java.lang.NoClassDefFoundError: 
org/aopalliance/aop/Advice</pre>
<p>The jars that are now required are: <em>spring-aop</em> (and implicitly <em>aopalliance</em>):</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
    &lt;groupId&gt;org.springframework&lt;/groupId&gt;
    &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
    &lt;version&gt;3.2.2.RELEASE&lt;/version&gt;
&lt;/dependency&gt;</pre>
<h2 id="conclusion"><strong>6. Conclusion</strong></h2>
<p>At the end of this article, we should have a clear map to navigate the variety of causes and problems that may lead to a <em>BeanDefinitionStoreException</em> as well as a good grasp on how to fix all of these problems.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/6UukbKirJ6w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-beandefinitionstoreexception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-beandefinitionstoreexception?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-beandefinitionstoreexception</feedburner:origLink></item>
		<item>
		<title>Maven Release to Nexus</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/6z_Pz8v1j-4/maven-release-nexus</link>
		<comments>http://www.baeldung.com/maven-release-nexus#comments</comments>
		<pubDate>Tue, 07 May 2013 12:13:32 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[maven]]></category>
		<category><![CDATA[nexus]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1970</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fd2adc8fc101007ce9"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Maven Release to Nexus - defining the repository in the pom, using the nexus release plugin, and the Release Process breakdown.]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949feecb2a1ea61008096"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2 id="overview"><strong>1. Overview</strong></h2>
<p>In the previous article of this series, we set up a <a title="Maven Deploy to Nexus" href="http://www.baeldung.com/maven-deploy-nexus" target="_blank"><strong>deployment process with Maven to Nexus</strong></a>. In this article, we&#8217;ll configure the <strong>Release Process with Maven</strong> &#8211; both in the <em>pom </em>of the project as well as in a Jenkins job.</p>
<h2 id="nexus"><strong>2. Repository in the <em>pom</em></strong></h2>
<p>In order for Maven to be able to release to a Nexus Repository Server, we need to <strong>define the repository</strong> information via the <em>distributionManagement</em> element:</p>
<pre class="brush: xml; gutter: true">&lt;distributionManagement&gt;
   &lt;repository&gt;
      &lt;id&gt;nexus-releases&lt;/id&gt;
      &lt;url&gt;http://localhost:8081/nexus/content/repositories/releases&lt;/url&gt;
   &lt;/repository&gt;
&lt;/distributionManagement&gt;</pre>
<p>The hosted Releases Repository comes out of the box on Nexus, so there is no need to create it explicitly.</p>
<h2 id="scm"><strong>3. SCM in the Maven <em>pom</em></strong></h2>
<p>The Release process will interact with the Source Control of the project &#8211; this means we first need to define the <em>&lt;scm&gt;</em> element in our <em>pom.xml</em>:</p>
<pre class="brush: xml; gutter: true">&lt;scm&gt;
   &lt;connection&gt;scm:git:https://github.com/user/project.git&lt;/connection&gt;
   &lt;url&gt;http://github.com/user/project&lt;/url&gt;
   &lt;developerConnection&gt;scm:git:https://github.com/user/project.git&lt;/developerConnection&gt;
&lt;/scm&gt;</pre>
<p>Or, using the git protocol:</p>
<pre class="brush: xml; gutter: true">&lt;scm&gt;
   &lt;connection&gt;scm:git:git@github.com:user/project.git&lt;/connection&gt;
   &lt;url&gt;scm:git:git@github.com:user/project.git&lt;/url&gt;
   &lt;developerConnection&gt;scm:git:git@github.com:user/project.git&lt;/developerConnection&gt;
&lt;/scm&gt;</pre>
<h2 id="release_plugin"><strong>3. The Release Plugin</strong></h2>
<p>The standard Maven plugin used by a Release Process is the <em>maven-release-plugin</em> &#8211; the configuration for this plugin is minimal:</p>
<pre class="brush: xml; gutter: true">&lt;plugin&gt;
   &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
   &lt;artifactId&gt;maven-release-plugin&lt;/artifactId&gt;
   &lt;version&gt;2.4.1&lt;/version&gt;
   &lt;configuration&gt;
      &lt;tagNameFormat&gt;v@{project.version}&lt;/tagNameFormat&gt;
      &lt;autoVersionSubmodules&gt;true&lt;/autoVersionSubmodules&gt;
      &lt;releaseProfiles&gt;releases&lt;/releaseProfiles&gt;
   &lt;/configuration&gt;
&lt;/plugin&gt;</pre>
<p>What is important here is that the <em>releaseProfiles</em> configuration will actually force a Maven profile &#8211; the <em>releases</em> profile &#8211; to become active during the Release process.</p>
<p>It is in this process that the <em>nexus-staging-maven-plugin</em> is used to perform a deploy to the <em>nexus-releases</em> Nexus repository:</p>
<pre class="brush: xml; gutter: true">&lt;profiles&gt;
   &lt;profile&gt;
      &lt;id&gt;releases&lt;/id&gt;
      &lt;build&gt;
         &lt;plugins&gt;
            &lt;plugin&gt;
               &lt;groupId&gt;org.sonatype.plugins&lt;/groupId&gt;
               &lt;artifactId&gt;nexus-staging-maven-plugin&lt;/artifactId&gt;
               &lt;version&gt;1.4.4&lt;/version&gt;
               &lt;executions&gt;
                  &lt;execution&gt;
                     &lt;id&gt;default-deploy&lt;/id&gt;
                     &lt;phase&gt;deploy&lt;/phase&gt;
                     &lt;goals&gt;
                        &lt;goal&gt;deploy&lt;/goal&gt;
                     &lt;/goals&gt;
                  &lt;/execution&gt;
               &lt;/executions&gt;
               &lt;configuration&gt;
                  &lt;serverId&gt;nexus-releases&lt;/serverId&gt;
                  &lt;nexusUrl&gt;http://localhost:8081/nexus/&lt;/nexusUrl&gt;
                  &lt;skipStaging&gt;true&lt;/skipStaging&gt;
               &lt;/configuration&gt;
            &lt;/plugin&gt;
         &lt;/plugins&gt;
      &lt;/build&gt;
   &lt;/profile&gt;
&lt;/profiles&gt;</pre>
<p>The plugin is configured to perform the Release process <strong>without the staging mechanism</strong>, same as <a title="Maven Deploy to Nexus" href="http://www.baeldung.com/maven-deploy-nexus" target="_blank">previously</a>, for the Deployment process (<em>skipStaging=true</em>).</p>
<p>And also similar to the Deployment process, <strong>Releasing to Nexus is a secured operation</strong> – so we&#8217;re going to use the Out of the Box <em>deployment</em> user form Nexus again.</p>
<p>We also need to configure the credentials for the <em>nexus-releases</em> server in the global <em>settings.xml</em> (<em>%USER_HOME%/.m2/settings.xml</em>):</p>
<pre class="brush: xml; gutter: true">&lt;servers&gt;
   &lt;server&gt;
      &lt;id&gt;nexus-releases&lt;/id&gt;
      &lt;username&gt;deployment&lt;/username&gt;
      &lt;password&gt;the_pass_for_the_deployment_user&lt;/password&gt;
   &lt;/server&gt;
&lt;/servers&gt;</pre>
<p>This is the full configuration</p>
<h2 id="release"><strong>4. The Release Process</strong></h2>
<p>Let&#8217;s break apart the release process into small and focused steps. We are performing a Release when the current version of the project is a SNAPSHOT version &#8211; say <em>0.1-SNAPSHOT</em>.</p>
<h3><strong>4.1. release:clean</strong></h3>
<p><strong>Cleaning a Release</strong> will:</p>
<ul>
<li>delete the release descriptor (<em>release.properties</em>)</li>
<li>delete any backup POM files</li>
</ul>
<p><strong>4.2. release:prepare</strong></p>
<p>Next part of the Release process is <strong>Preparing the Release</strong>; this will:</p>
<ul>
<li>perform some checks &#8211; there should be no uncommitted changes and the project should depend on no SNAPSHOT dependencies</li>
<li>change the version of the project in the pom file to a full release number (remove SNAPSHOT suffix) &#8211; in our example &#8211; <em>0.1</em></li>
<li>run the project <strong>test</strong> suites</li>
<li>commit and push the changes</li>
<li>create the <strong>tag</strong> out of this non-SNAPSHOT versioned code</li>
<li><strong>increase the version</strong> of the project in the pom &#8211; in our example &#8211; <em>0.2-SNAPSHOT</em></li>
<li>commit and push the changes</li>
</ul>
<p><strong>4.3. release:perform</strong></p>
<p>The latter part of the Release process is <strong>Performing the Release</strong>; this will:</p>
<ul>
<li>checkout release tag from SCM</li>
<li>build and deploy released code</li>
</ul>
<p>This second step of the process relies on the output of the Prepare step - the <em>release.properties</em>.</p>
<h2 id="jenkins"><strong>5. On Jenkins</strong></h2>
<p>Jenkins can perform the release process in one of two ways &#8211; it can either use it&#8217;s own release plugins, or it can simply run perform the release with a standard maven job running the correct release steps.</p>
<p>The existing Jenkins plugins focused on the release process are:</p>
<ul>
<li><a title="The Jenkins Release Plugin" href="https://wiki.jenkins-ci.org/display/JENKINS/Release+Plugin" target="_blank">Release Plugin</a></li>
<li><a title="The M2 Jenkins Release Plugin" href="https://wiki.jenkins-ci.org/display/JENKINS/M2+Release+Plugin" target="_blank">M2 Release Plugin</a></li>
</ul>
<p>However, since the Maven command for performing the release is simple enough, we can simply define a standard Jenkins job to perform the operation &#8211; no plugins necessary.</p>
<p>So, for a new Jenkins job (Build a maven2/3 project) &#8211; we&#8221;ll define 2 String parameters: <em>releaseVersion=0.1</em> and <em>developmentVersion=0.2-SNAPSHOT</em>.</p>
<p>At the <em><strong>Build</strong></em> configuration section, we can simply configure the following Maven command to run:</p>
<pre class="brush: shell; gutter: true">release:clean release:prepare release:perform 
   -DreleaseVersion=${releaseVersion} -DdevelopmentVersion=${developmentVersion}</pre>
<p>When running a parametrized job, Jenkins will prompt the user to specify values for these parameters &#8211; so each time we run the job we need to fill in the right values for <em>releaseVersion</em> and <em>developmentVersion</em>.</p>
<p>Also, it&#8217;s worth using the <a title="Jenkins Workspace Cleanup Plugin" href="https://wiki.jenkins-ci.org/display/JENKINS/Workspace+Cleanup+Plugin" target="_blank">Workspace Cleanup Plugin</a> and check the <em>Delete workspace before build starts</em> option for this build. However keep in mind that the <strong><em>perform</em></strong> step of the Release should necessarily be run by the same command as the <em><strong>prepare</strong></em><strong> </strong>step &#8211; this is because the latter <em><strong>perform</strong></em> step will use the <em>release.properties</em> file created by <em><strong>prepare</strong></em>. This means that we cannot have a Jenkins Job running <em><strong>prepare</strong> </em>and another running <em><strong>perform</strong></em>.</p>
<h2 id="conclusion"><strong>6. Conclusion</strong></h2>
<p>This article showed how to implement the process o<strong></strong>f <strong>Releasing a Maven project</strong> with or without Jenkins. Similar <a title="Maven Deploy to Nexus" href="http://www.baeldung.com/maven-deploy-nexus" target="_blank">to Deployment</a>, this process is using the <em>nexus-staging-maven-plugin</em> to interact with Nexus and focuses on a git project.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/6z_Pz8v1j-4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/maven-release-nexus/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/maven-release-nexus?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=maven-release-to-nexus</feedburner:origLink></item>
		<item>
		<title>Hibernate 3 with Spring</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/bLRYEf7BkzQ/hibernate3-spring</link>
		<comments>http://www.baeldung.com/hibernate3-spring#comments</comments>
		<pubDate>Sun, 05 May 2013 18:22:16 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[Persistence]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Hibernate]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1968</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949feecb2a1147e00e3d7"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Hibernate 3 with Spring - The Java and XML Configuration, integration with MySQL and usage best practices.]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fe2adc8fc201007e8d"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2 id="overview"><strong>1. Overview</strong></h2>
<p>This article will focus on setting up <strong>Hibernate 3 with Spring</strong> &#8211; we&#8217;ll look at how to use both XML and Java configuration to set up Spring 3 with Hibernate 3 and MySQL.</p>
<h2 id="java_config"><strong>2. Java </strong><strong>Spring Configuration for Hibernate 3</strong></h2>
<p>Setting up Hibernate 3 with Spring and Java config is straightforward:</p>
<pre class="brush: java; gutter: true">import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;

@Configuration
@EnableTransactionManagement
@PropertySource({ &quot;classpath:persistence-mysql.properties&quot; })
@ComponentScan({ &quot;org.baeldung.spring.persistence&quot; })
public class PersistenceConfig {

   @Autowired
   private Environment env;

   @Bean
   public AnnotationSessionFactoryBean sessionFactory() {
      AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
      sessionFactory.setDataSource(restDataSource());
      sessionFactory.setPackagesToScan(new String[] { &quot;org.baeldung.spring.persistence.model&quot; });
      sessionFactory.setHibernateProperties(hibernateProperties());

      return sessionFactory;
   }

   @Bean
   public DataSource restDataSource() {
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(env.getProperty(&quot;jdbc.driverClassName&quot;));
      dataSource.setUrl(env.getProperty(&quot;jdbc.url&quot;));
      dataSource.setUsername(env.getProperty(&quot;jdbc.user&quot;));
      dataSource.setPassword(env.getProperty(&quot;jdbc.pass&quot;));

      return dataSource;
   }

   @Bean
   public HibernateTransactionManager transactionManager() {
      HibernateTransactionManager txManager = new HibernateTransactionManager();
      txManager.setSessionFactory(sessionFactory().getObject());

      return txManager;
   }

   @Bean
   public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
      return new PersistenceExceptionTranslationPostProcessor();
   }

   Properties hibernateProperties() {
      return new Properties() {
         {
            setProperty(&quot;hibernate.hbm2ddl.auto&quot;, env.getProperty(&quot;hibernate.hbm2ddl.auto&quot;));
            setProperty(&quot;hibernate.dialect&quot;, env.getProperty(&quot;hibernate.dialect&quot;));
         }
      };
   }
}</pre>
<p>Compared to the XML Configuration &#8211; described next &#8211; there is a small difference in the way one bean in the configuration access another. In XML there is no difference between <strong>pointing to a bean or pointing to a bean factory capable of creating that bean</strong>. Since the Java configuration is type-safe &#8211; pointing directly to the bean factory is no longer an option &#8211; we need to retrieve the bean from the bean factory manually:</p>
<pre class="brush: java; gutter: true">txManager.setSessionFactory(sessionFactory().getObject());</pre>
<h2 id="xml_config"><strong>3. XML Spring Configuration for Hibernate 3</strong></h2>
<p>Similarly, we can set up<strong> Hibernate 3 with XML config</strong> as well:<br />

<pre class="brush: xml; gutter: true">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot; 
   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; 
   xmlns:context=&quot;http://www.springframework.org/schema/context&quot;
   xsi:schemaLocation=&quot;
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.2.xsd&quot;&gt;

   &lt;context:property-placeholder location=&quot;classpath:persistence-mysql.properties&quot; /&gt;

   &lt;bean id=&quot;sessionFactory&quot; 
    class=&quot;org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean&quot;&gt;
      &lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot; /&gt;
      &lt;property name=&quot;packagesToScan&quot; value=&quot;org.baeldung.spring.persistence.model&quot; /&gt;
      &lt;property name=&quot;hibernateProperties&quot;&gt;
         &lt;props&gt;
            &lt;prop key=&quot;hibernate.hbm2ddl.auto&quot;&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;
            &lt;prop key=&quot;hibernate.dialect&quot;&gt;${hibernate.dialect}&lt;/prop&gt;
         &lt;/props&gt;
      &lt;/property&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;dataSource&quot; 
    class=&quot;org.springframework.jdbc.datasource.DriverManagerDataSource&quot;&gt;
      &lt;property name=&quot;driverClassName&quot; value=&quot;${jdbc.driverClassName}&quot; /&gt;
      &lt;property name=&quot;url&quot; value=&quot;${jdbc.url}&quot; /&gt;
      &lt;property name=&quot;username&quot; value=&quot;${jdbc.user}&quot; /&gt;
      &lt;property name=&quot;password&quot; value=&quot;${jdbc.pass}&quot; /&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;txManager&quot; 
    class=&quot;org.springframework.orm.hibernate3.HibernateTransactionManager&quot;&gt;
      &lt;property name=&quot;sessionFactory&quot; ref=&quot;sessionFactory&quot; /&gt;
   &lt;/bean&gt;

   &lt;bean id=&quot;persistenceExceptionTranslationPostProcessor&quot; 
    class=&quot;org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor&quot;/&gt;

&lt;/beans&gt;</pre>
</p>
<p>Then, this XML file is boostrapped into the Spring context using a <em>@Configuration</em> class:</p>
<pre class="brush: java; gutter: true">@Configuration
@EnableTransactionManagement
@ImportResource({ &quot;classpath:persistenceConfig.xml&quot; })
public class PersistenceXmlConfig {
   //
}</pre>
<p>For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file:</p>
<pre class="brush: shell; gutter: true"># jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop</pre>
<h2 id="mysql"><strong>4. Spring, Hibernate and MySQL</strong></h2>
<p>The example above uses MySQL 5 as the underlying database configured with Hibernate &#8211; however, Hibernate supports several underlying <a title="Hibernate Supported Databases" href="https://community.jboss.org/wiki/SupportedDatabases2" target="_blank">SQL Databases</a>.</p>
<h3><strong>4.1. The Driver</strong></h3>
<p>The Driver class name is configured via <strong>the <em>jdbc.driverClassName</em> property</strong> provided to the DataSource.</p>
<p>In the example above, it is set to <em>com.mysql.jdbc.Driver</em> from the <em>mysql-connector-java</em> dependency we defined in the pom, at the start of the article.</p>
<h3><strong>4.2. The Dialect</strong></h3>
<p>The Dialect is configured via <strong>the <em>hibernate.dialect</em> property</strong> provided to the Hibernate <em>SessionFactory</em>.</p>
<p>In the example above, this is set to <em>org.hibernate.dialect.MySQL5Dialect</em> as we are using MySQL 5 as the underlying Database. There are several <strong>other dialects supporting MySQL</strong>:</p>
<ul>
<li><em><strong>org.hibernate.dialect.MySQL5InnoDBDialect</strong></em> &#8211; for MySQL 5.x with the InnoDB storage engine</li>
<li><em><strong>org.hibernate.dialect.MySQLDialect</strong></em> &#8211; for MySQL prior to 5.x</li>
<li><em><strong>org.hibernate.dialect.MySQLInnoDBDialect</strong></em> &#8211; for MySQL prior to 5.x with the InnoDB storage engine</li>
<li><em><strong>org.hibernate.dialect.MySQLMyISAMDialect</strong></em> &#8211; for all MySQL versions with the ISAM storage engine</li>
</ul>
<p>Hibernate <a title="Hibernate Supported Dialects" href="http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-optional-dialects" target="_blank">supports SQL Dialects</a> for every supported Database.</p>
<h2 id="usage"><strong>5. Usage</strong></h2>
<p>At this point, Hibernate 3 is fully configured with Spring and we can<strong> inject the raw Hibernate</strong> <em>SessionFactory</em> directly whenever we need to:</p>
<pre class="brush: java; gutter: true">public abstract class FooHibernateDAO{

   @Autowired
   SessionFactory sessionFactory;

   ...

   protected Session getCurrentSession(){
      return sessionFactory.getCurrentSession();
   }
}</pre>
<h2 id="maven"><strong>6. Maven</strong></h2>
<p>To add the Spring Persistence dependencies to the pom, please see the <a title="Spring with Maven - Persistence" href="http://www.baeldung.com/spring-with-maven#persistence">Spring with Maven article</a> &#8211; we&#8217;ll need to define both <em>spring-context</em> and <em>spring-orm</em>.</p>
<p>Continuing to Hibernate 3, the Maven dependencies are simple:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
   &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
   &lt;version&gt;3.6.10.Final&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>Then, to enable Hibernate to use its proxy model, we need <em>javassist</em> as well:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;org.javassist&lt;/groupId&gt;
   &lt;artifactId&gt;javassist&lt;/artifactId&gt;
   &lt;version&gt;3.17.1-GA&lt;/version&gt;
&lt;/dependency&gt;</pre>
<p>And since we&#8217;re going to use MySQL for this tutorial, we&#8217;ll also need:</p>
<pre class="brush: xml; gutter: true">&lt;dependency&gt;
   &lt;groupId&gt;mysql&lt;/groupId&gt;
   &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
   &lt;version&gt;5.1.25&lt;/version&gt;
   &lt;scope&gt;runtime&lt;/scope&gt;
&lt;/dependency&gt;</pre>
<h2 id="conclusion"><strong>7. Conclusion</strong></h2>
<p>In this example, <strong>we configured Hibernate 3 with Spring</strong> &#8211; both with Java and XML configuration. The implementation of this simple project can be found in <a title="Spring with Hibernate 3 Project on Github" href="https://github.com/eugenp/tutorials/tree/master/spring-hibernate3" target="_blank">the github project</a> – this is an Eclipse based project, so it should be easy to import and run as it is.</p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/bLRYEf7BkzQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/hibernate3-spring/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/hibernate3-spring?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=hibernate-3-with-spring</feedburner:origLink></item>
		<item>
		<title>Tweeting StackExchange Questions with Spring Social</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/6GjfqmcuWxM/tweeting-stackexchange</link>
		<comments>http://www.baeldung.com/tweeting-stackexchange#comments</comments>
		<pubDate>Fri, 03 May 2013 21:27:48 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[REST]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1963</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949fe2adc8fc101007cea"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Tweeting StackExchange Questions with Spring Social]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949ffecb2a1ea61008097"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2><strong>1. Introduction</strong></h2>
<p>This is the third and final article about a small side-project &#8211; a bot that automatically tweets Questions from various Q&amp;A StackExchange sites on specialized accounts (full list at the end of the article).</p>
<p>The <a title="StackExchange REST Client with Spring and RestTemplate" href="http://www.baeldung.com/tweeting-stackexchange-with-spring-social-part-1/">first article</a> discussed building a <a title="Client for the Stackexchange REST API on github" href="https://github.com/eugenp/java-stackexchange" target="_blank">simple client</a> for the StackExchange REST API. In the <a title="Spring Social Twitter Setup" href="http://www.baeldung.com/spring_social_twitter_setup">second article</a> we set up the interaction with Twitter using Spring Social.</p>
<p>This article will describe the final part of the implementation &#8211; the part responsible with the interaction between the Stackexchange client and the <em>TwitterTemplate</em>.</p>
<h2><strong>2. The Tweet Stackexchange Service</strong></h2>
<p>The interaction between the Stackexchange Client &#8211; exposing the raw Questions, and the <em>TwitterTemplate</em> &#8211; fully set up and able to tweet &#8211; is a very simple service &#8211; the <em>TweetStackexchangeService</em>. The API published by this is:</p>
<pre class="brush: java; gutter: true">public void tweetTopQuestionBySite(String site, String twitterAccount){ ... }
public void tweetTopQuestionBySiteAndTag(String site, String twitterAccount, String tag){ ... }</pre>
<p>The functionality is simple &#8211; these APIs will keep reading Questions from the Stackexchange REST API (through the client), until one is found that <strong>has not been tweeted before</strong> on that particular account.</p>
<p>When that question is found, it is <strong>tweeted via the <em>TwitterTemplate</em> </strong>corresponding to that account, and a very simple <em>Question</em> entity is saved locally. This entity is only storing the id of the Question and the Twitter Account that it has been tweeted on.</p>
<p><strong>For example</strong> the following question:</p>
<p><a title="Binding a list in @RequestParam" href="http://stackoverflow.com/questions/4596351/binding-a-list-in-requestparam" target="_blank">Binding a list in @RequestParam</a></p>
<p><a title="Tweet on Binding a list in @RequestParam" href="https://twitter.com/SpringAtSO/status/326561270604103680" target="_blank">Has been tweeted</a> on the <a title="SpringAtSO twitter account" href="https://twitter.com/SpringAtSO" target="_blank">SpringAtSO</a> account.</p>
<p>The Question entity simply contains:</p>
<ul>
<li>the <strong>id of the Question</strong> &#8211; 4596351 in this case</li>
<li>the <strong>Twitter Account</strong> on which the question has been tweeted &#8211; SpringAtSO</li>
<li>the <strong>Stackexcange Site</strong> from which the question originates &#8211; Stackoverflow</li>
</ul>
<p>We need to keep track of this information so that we know which questions have already been tweeted and which haven&#8217;t.</p>
<h2><strong>3. The Scheduler</strong></h2>
<p>The scheduler makes use of the Spring&#8217;s scheduled task capabilities &#8211; these are enabled via the Java configuration:</p>
<pre class="brush: java; gutter: true">@Configuration
@EnableScheduling
public class ContextConfig {
   //
}</pre>
<p>The actual scheduler is relativelly simple:</p>
<pre class="brush: java; gutter: true">@Component
@Profile(SpringProfileUtil.DEPLOYED)
public class TweetStackexchangeScheduler {

   @Autowired
   private TweetStackexchangeService service;

   // API

   @Scheduled(cron = &quot;0 0 1,5 * * *&quot;)
   public void tweetStackExchangeTopQuestion() throws JsonProcessingException, IOException {
      service.tweetTopQuestionBySiteAndTag(&quot;StackOverflow&quot;, Tag.clojure.name(), &quot;BestClojure&quot;, 1);
      String randomSite = StackexchangeUtil.pickOne(&quot;SuperUser&quot;, &quot;StackOverflow&quot;);
      service.tweetTopQuestionBySiteAndTag(randomSite, Tag.bash.name(), &quot;BestBash&quot;, 1);
   }
}</pre>
<p>There are two tweet operations configured above &#8211; one tweets from StackOverflow questions which are tagged with &#8220;clojure&#8221; on the <a title="Best Of Clojure on Twitter" href="https://twitter.com/BestClojure" target="_blank">Best Of Clojure twitter account</a>.</p>
<p>The other operation tweets questions tagged with &#8220;bash&#8221; &#8211; and because these kind of questions actually appear on multiple sites from the Stackexchange network: <a title="bash on stackoverflow" href="http://stackoverflow.com/questions/tagged/bash" target="_blank">StackOverflow</a>, <a title="bash on superuser" href="http://superuser.com/questions/tagged/bash" target="_blank">SuperUser </a>and <a title="bash on askubuntu" href="http://askubuntu.com/questions/tagged/bash" target="_blank">AskUbuntu</a>, there is first a quick selection process to pick one of these sites, after which the question is tweeted.</p>
<p>Finally, the <strong>cron job is scheduled to run</strong> at 1 AM and 5 AM each day.</p>
<h2><strong>4. Setup</strong></h2>
<p>This being a pet project, it started out with a <strong>very simple database structure</strong> &#8211; it&#8217;s still simple now, but it was even more so. So one of the main goals was to be able to easily change the database structure &#8211; there are of course <a title="Database Migrations And Java" href="http://techblog.bozho.net/?p=1100" target="_blank">several tools </a>for database migrations, but they&#8217;re all overkill for such a simple project.</p>
<p>So I decided to keep setup data in <a title="Setup Data on Github" href="https://github.com/eugenp/stackexchange2twitter/blob/master/src/main/resources/setup.properties" target="_blank">a simple text format</a> &#8211; that is going to be updated semi-automatically.</p>
<p>Setup has two main steps:</p>
<ul>
<li>the ids of the questions tweeted on each twitter account are retrieved and stored in a text file</li>
<li>the database schema is dropped and the application restarted &#8211; this will create the schema again and setup all data from the text file back into the new database</li>
</ul>
<h3><strong>4.1. The Raw Setup Data</strong></h3>
<p>The process of retrieving the data the existing database is simple enough with JDBC; first we define a RowMapper:</p>
<pre class="brush: java; gutter: true">class TweetRowMapper implements RowMapper&lt;String&gt; {
   private Map&lt;String, List&lt;Long&gt;&gt; accountToQuestions;

   public TweetRowMapper(Map&lt;String, List&lt;Long&gt;&gt; accountToQuestions) {
      super();
      this.accountToQuestions = accountToQuestions;
   }

   public String mapRow(ResultSet rs, int line) throws SQLException {
      String questionIdAsString = rs.getString(&quot;question_id&quot;);
      long questionId = Long.parseLong(questionIdAsString);
      String account = rs.getString(&quot;account&quot;);

      if (accountToQuestions.get(account) == null) {
         accountToQuestions.put(account, Lists.&lt;Long&gt; newArrayList());
      }
      accountToQuestions.get(account).add(questionId);
      return &quot;&quot;;
   }
}</pre>
<p>This will build a list of Questions for each Twitter account.</p>
<p>Next, we&#8217;re going to use this in a simple test:</p>
<pre class="brush: java; gutter: true">@Test
public void whenQuestionsAreRetrievedFromTheDB_thenNoExceptions() {
   Map&lt;String, List&lt;Long&gt;&gt; accountToQuestionsMap = Maps.newHashMap();
   jdbcTemplate.query
      (&quot;SELECT * FROM question_tweet;&quot;, new TweetRowMapper(accountToQuestionsMap));

   for (String accountName : accountToQuestionsMap.keySet()) {
      System.out.println
         (accountName + &quot;=&quot; + valuesAsCsv(accountToQuestionsMap.get(accountName)));
   }
}</pre>
<p>After retrieving the Questions for an account, the test will simply list them out; for example:</p>
<pre class="brush: bash; gutter: true">SpringAtSO=3652090,1079114,5908466,...</pre>
<h3><strong>4.2. Restoring the Setup Data</strong></h3>
<p>The lines of data generated by the previous step are stored in <a title="Setup Data on Github" href="https://github.com/eugenp/stackexchange2twitter/blob/master/src/main/resources/setup.properties" target="_blank">a <em>setup.properties</em> file</a> which is made available to Spring:</p>
<pre class="brush: java; gutter: true">@Configuration
@PropertySource({ &quot;classpath:setup.properties&quot; })
public class PersistenceJPAConfig {
   //
}</pre>
<p>When the application starts up, the setup process is performed. This simple process uses a Spring ApplicationListener, listening on a <em>ContextRefreshedEvent</em>:</p>
<pre class="brush: java; gutter: true">@Component
public class StackexchangeSetup implements ApplicationListener&lt;ContextRefreshedEvent&gt; {
    private boolean setupDone;

    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (!setupDone) {
            recreateAllQuestionsOnAllTwitterAccounts();
            setupDone = true;
        }
    }
}</pre>
<p>Finally, the questions are retrieved from the <em>setup.properties</em> file and recreated:</p>
<pre class="brush: java; gutter: true">private void recreateAllQuestionsOnTwitterAccount(String twitterAccount) {
   String tweetedQuestions = env.getProperty(twitterAccount.name();
   String[] questionIds = tweetedQuestions.split(&quot;,&quot;);
   recreateQuestions(questionIds, twitterAccount);
}
void recreateQuestions(String[] questionIds, String twitterAccount) {
   List&lt;String&gt; stackSitesForTwitterAccount = twitterAccountToStackSites(twitterAccount);
   String site = stackSitesForTwitterAccount.get(0);
   for (String questionId : questionIds) {
      QuestionTweet questionTweet = new QuestionTweet(questionId, twitterAccount, site);
      questionTweetDao.save(questionTweet);
   }
}</pre>
<p>This simple process allows easy updates of the DB structure &#8211; since the data is fully erased and fully re-created, there is <strong>no need to do any actual migration</strong> whatsoever.</p>
<h2><strong>5. Full List of Accounts</strong></h2>
<p>The <strong>full list of Twitter accounts</strong> is:</p>
<ul>
<li><a title="Spring At SO Account on Twitter" href="https://twitter.com/SpringAtSO" target="_blank">SpringAtSO</a> &#8211; <strong>Spring</strong> questions from StackOverflow</li>
<li><a title="Java At SO Account on Twitter" href="https://twitter.com/JavaTopSO" target="_blank">JavaTopSO </a>- <strong>Java</strong> questions from StackOverflow</li>
<li><a title="Best REST Account on Twitter" href="https://twitter.com/RESTDaily" target="_blank">RESTDaily</a> &#8211; <strong>REST</strong> questions from StackOverflow</li>
<li><a title="Best JPA Account on Twitter" href="https://twitter.com/BestJPA" target="_blank">BestJPA </a>- <strong>JPA</strong> questions from StackOverflow</li>
<li><a title="Best Maven Account on Twitter" href="https://twitter.com/BestMaven" target="_blank">BestMaven</a> &#8211; <strong>Maven</strong> questions from StackOverflow</li>
<li><a title="Best Git Account on Twitter" href="https://twitter.com/BestGit" target="_blank">BestGit </a>- <strong>Git</strong> questions from StackOverflow</li>
<li><a title="AskUbuntu Best Account on Twitter" href="https://twitter.com/AskUbuntuBest" target="_blank">AskUbuntuBest </a>- <strong>AskUbuntu</strong> best overal questions (all topics)</li>
<li><a title="ServerFault Best Account on Twitter" href="https://twitter.com/ServerFaultBest" target="_blank">ServerFaultBest</a> &#8211; <strong>ServerFault</strong> best questions (all topics)</li>
<li><a title="Best Bash Account on Twitter" href="https://twitter.com/BestBash" target="_blank">BestBash</a> &#8211; <strong>best Bash questions</strong> from StackOverflow, ServerFault and AskUbuntu</li>
<li><a title="Clojure At SO Account on Twitter" href="https://twitter.com/BestClojure" target="_blank">BestClojure</a> &#8211; Clojure questions from StackOverflow</li>
<li><a title="Scala At SO Account on Twitter" href="https://twitter.com/BestScala" target="_blank">BestScala</a> &#8211; Scala questions from StackOverflow</li>
<li><a title="Eclipse At SO Account on Twitter" href="https://twitter.com/BestEclipse" target="_blank">BestEclipse</a> - Eclipse questions from StackOverflow</li>
<li><a title="jQuery At SO Account on Twitter" href="https://twitter.com/jQueryDaily" target="_blank">jQueryDaily</a> &#8211; jQuery questions from StackOverflow</li>
<li><a title="Algorithms At SO Account on Twitter" href="https://twitter.com/BestAlgorithms" target="_blank">BestAlgorithms</a> &#8211; Algorithm questions from StackOverflow</li>
</ul>
<p>2 tweets per day are created on each of these accounts, with the highest rated questions on their specific subject.</p>
<h2><strong>6. Conclusion</strong></h2>
<p>This third article finishes the series about integrating with StackOverflow and other StackExchange sites to retrieve questions through their REST API, and integrating with Twitter and Spring Social to tweet these questions. A potential direction worth exporing is doing the same with Google Plus &#8211; probably using Pages, not accounts.</p>
<p><strong>14 Twitter accounts</strong> are up and running as a result of this project &#8211; focusing on various topics and producing low volume and hopefully high quality content (ideas for other tags that deserves their own Twitter account are welcome in the comments).</p>
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/6GjfqmcuWxM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/tweeting-stackexchange/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/tweeting-stackexchange?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=tweeting-stackexchange-questions-with-spring-social</feedburner:origLink></item>
		<item>
		<title>Spring Security Form Login</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/a8q7_QMcvYI/spring-security-login</link>
		<comments>http://www.baeldung.com/spring-security-login#comments</comments>
		<pubDate>Wed, 01 May 2013 14:13:14 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1944</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949ffecb2a1757f00e3c7"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>A Spring Login Example - How to Set Up a simple Login Form, a Basic Security XML Configuration and some more Advanced Configuration Techniques.]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949ffecb2a13364007de4"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><p><span style="color: #ff6600;"><strong>Last Update</strong></span>: <span style="color: #999999;"><strong>19.05.2013 (2nd update)</strong></span></p>
<h2 id="introduction"><strong>1. Introduction</strong></h2>
<p>This article is going to focus on <strong>Login with Spring Security</strong>. We&#8217;re going to built on top of the simple <a title="Spring MVC Tutorial" href="http://www.baeldung.com/spring-mvc-tutorial">Spring MVC example</a>, as Spring MVC is a necessary part of setting up the login mechanism.</p>
<h2 id="maven"><strong>2. The Maven Dependencies</strong></h2>
<p>To add Maven dependencies to the project, please see the <a title="Spring Security with Maven" href="http://www.baeldung.com/spring-security-with-maven">Spring Security with Maven article</a>. Both standard <em>spring-security-web</em> and <em>spring-security-config</em> will be required.</p>
<h2 id="web_xml"><strong>3. The <em>web.xml</em></strong></h2>
<p>The Spring Security configuration in the <em>web.xml</em> is simple &#8211; only an additional filter added to the standard Spring MVC <em>web.xml</em>: <em></em></p>

<pre class="brush: xml; gutter: true">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
   xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; 
   xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;
   xsi:schemaLocation=&quot;
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot; 
   id=&quot;WebApp_ID&quot; version=&quot;3.0&quot;&gt;

   &lt;display-name&gt;Spring Secured Application&lt;/display-name&gt;

   &lt;!-- Spring MVC --&gt;
   &lt;servlet&gt;
      &lt;servlet-name&gt;mvc&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
   &lt;/servlet&gt;
   &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;mvc&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;

   &lt;context-param&gt;
      &lt;param-name&gt;contextClass&lt;/param-name&gt;
      &lt;param-value&gt;
         org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      &lt;/param-value&gt;
   &lt;/context-param&gt;
   &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;org.baeldung.spring.web.config&lt;/param-value&gt;
   &lt;/context-param&gt;
   &lt;listener&gt;
      &lt;listener-class&gt;
         org.springframework.web.context.ContextLoaderListener
      &lt;/listener-class&gt;
   &lt;/listener&gt;

   &lt;!-- Spring Security --&gt;
   &lt;filter&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt;
   &lt;/filter&gt;
   &lt;filter-mapping&gt;
      &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt;
      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
   &lt;/filter-mapping&gt;

&lt;/web-app&gt;</pre>

<p>The filter &#8211; <em>DelegatingFilterProxy</em> &#8211; simply delegates to a Spring managed bean &#8211; the <em>FilterChainProxy</em> &#8211; which itself is able to benefit from full Spring bean lifecycle management and such.</p>
<h2 id="configuration"><strong>2. The Spring Security configuration</strong></h2>
<p>The Spring configuration is mostly written in Java, but Spring Security configuration doesn&#8217;t yet support full Java and still needs to be XML for the most part. There is an ongoing effort to add <a title="Spring Security Java based Configuration" href="https://github.com/SpringSource/spring-security-javaconfig" target="_blank">Java based configuration for Spring Security</a>, but this is not yet mature.</p>
<p>The overall project is using Java configuration, so the XML configuration file needs to be imported via a Java <em>@Configuration</em> class:</p>
<pre class="brush: java; gutter: true">@Configuration
@ImportResource({ &quot;classpath:webSecurityConfig.xml&quot; })
public class SecSecurityConfig {
   public SecSecurityConfig() {
      super();
   }
}</pre>
<p>The Spring Security XML Configuration &#8211; <em>webSecurityConfig.xml</em>:</p>

<pre class="brush: xml; gutter: true">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans:beans xmlns=&quot;http://www.springframework.org/schema/security&quot; 
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
  xmlns:beans=&quot;http://www.springframework.org/schema/beans&quot;
  xsi:schemaLocation=&quot;
      http://www.springframework.org/schema/security 
      http://www.springframework.org/schema/security/spring-security-3.1.xsd
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd&quot;&gt;

   &lt;http use-expressions=&quot;true&quot;&gt;
      &lt;intercept-url pattern=&quot;/login*&quot; access=&quot;isAnonymous()&quot; /&gt;
      &lt;intercept-url pattern=&quot;/**&quot; access=&quot;isAuthenticated()&quot;/&gt;

      &lt;form-login 
         login-page=&#039;/login.html&#039; 
         default-target-url=&quot;/homepage.html&quot; 
         authentication-failure-url=&quot;/login.html?error=true&quot; /&gt;

      &lt;logout logout-success-url=&quot;/login.html&quot; /&gt;

   &lt;/http&gt;
   &lt;authentication-manager&gt;
      &lt;authentication-provider&gt;
         &lt;user-service&gt;
            &lt;user name=&quot;user1&quot; password=&quot;user1Pass&quot; authorities=&quot;ROLE_USER&quot; /&gt;
         &lt;/user-service&gt;
      &lt;/authentication-provider&gt;
   &lt;/authentication-manager&gt;
&lt;/beans:beans&gt;</pre>

<h3><strong>2.1. <em>&lt;intercept-url&gt;</em></strong></h3>
<p>We are allowing anonymous access on <em>/login</em> so that users can authenticate. We are also securing everything else.</p>
<p>Note that the <strong>order of the <em>&lt;intercept-url&gt;</em></strong> element is significant &#8211; the more specific rules need to come first, followed by the more general ones.</p>
<h3><strong>2.2. <em>&lt;form-login&gt;</em></strong></h3>
<ul>
<li><em>login-page</em> &#8211; the <strong>custom login page</strong></li>
<li><em>default-target-url</em> &#8211; the landing page after a successful login</li>
<li><em>authentication-failure-url</em> &#8211; the landing page after an unsuccessful login</li>
</ul>
<h3><strong>2.3. <em>&lt;logout&gt;</em></strong></h3>
<p>The <em>&lt;logout&gt;</em> element is simply configured to go back to the login page.</p>
<h3><strong>2.4. <em>&lt;authentication-manager&gt;</em></strong></h3>
<p>The Authentication Provider is backed by a simple, in-memory implementation &#8211; <em>InMemoryUserDetailsManager</em> specifically  &#8211; configured in plain text. This only exists in Spring 3.1 and above and is meant to be used for rapid prototyping when a full persistence mechanism is not yet necessary.</p>
<h2 id="login-form"><strong>3. The Login Form</strong></h2>
<p>The login form page is going to be registered with Spring MVC using the straightforward mechanism to <a title="Spring MVC View Configuration" href="http://www.baeldung.com/spring-mvc-tutorial#configviews" target="_blank">map views names to URLs</a> with no need for an explicit controller in between:</p>
<pre class="brush: java; gutter: true">   registry.addViewController(&quot;/login.html&quot;);</pre>
<p>This of course corresponds to the <em>login.jsp</em>:</p>
<pre class="brush: xml; gutter: true">&lt;html&gt;
&lt;head&gt;&lt;/head&gt;
&lt;body&gt;
   &lt;h1&gt;Login&lt;/h1&gt;
   &lt;form name=&#039;f&#039; action=&quot;j_spring_security_check&quot; method=&#039;POST&#039;&gt;
      &lt;table&gt;
         &lt;tr&gt;
            &lt;td&gt;User:&lt;/td&gt;
            &lt;td&gt;&lt;input type=&#039;text&#039; name=&#039;j_username&#039; value=&#039;&#039;&gt;&lt;/td&gt;
         &lt;/tr&gt;
         &lt;tr&gt;
            &lt;td&gt;Password:&lt;/td&gt;
            &lt;td&gt;&lt;input type=&#039;password&#039; name=&#039;j_password&#039; /&gt;&lt;/td&gt;
         &lt;/tr&gt;
         &lt;tr&gt;
            &lt;td&gt;&lt;input name=&quot;submit&quot; type=&quot;submit&quot; value=&quot;submit&quot; /&gt;&lt;/td&gt;
         &lt;/tr&gt;
      &lt;/table&gt;
  &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>The <strong>Spring Login form</strong> has the following relevant artifacts:</p>
<ul>
<li><em>j_spring_security_check</em> &#8211; the URL where the form is POSTed to trigger the authentication process</li>
<li><em>j_username</em> &#8211; the user name</li>
<li><em>j_password</em> &#8211; the password</li>
</ul>
<h2 id="spring-login-configuration"><strong>4. <strong>Further</strong> Configuring Spring Login<br />
</strong></h2>
<p>We briefly discussed a few configurations of the login mechanism when we introduced the Spring Security XML Configuration above &#8211; let&#8217;s go into some detail now.</p>
<p>One reason to override most of the defaults in Spring Security is to <strong>hide the fact that the application is secured with Spring Security</strong> and minimize the information a potential attacker knows about the application.</p>
<p>Fully configured, the <em>&lt;form-login&gt;</em> element looks like this:</p>
<pre class="brush: xml; gutter: true">&lt;form-login 
   login-page=&#039;/login.html&#039; 
   login-processing-url=&quot;/perform_login&quot; 
   default-target-url=&quot;/homepage.html&quot;
   authentication-failure-url=&quot;/login.html?error=true&quot; 
   always-use-default-target=&quot;true&quot;/&gt;</pre>
<h3><strong>4.1. The Login page</strong></h3>
<p>The custom login page is configured via the <em>login-page</em> attribute o<em>n &lt;form-login&gt;</em>:</p>
<pre class="brush: xml; gutter: true">login-page=&#039;/login.html&#039;</pre>
<p>If this is not specified, a default URL is used &#8211; <em>spring_security_login</em> &#8211; and Spring Security will generate a very basic Login Form at that URL.</p>
<h3><strong>4.2. The POST URL for Login</strong></h3>
<p>The default URL where the Spring Login will POST to trigger the authentication process is <em>/j_spring_security_check</em>.</p>
<p>This URL can be overridden via the <em>login-processing-url</em> attribute on <em>&lt;form-login&gt;</em>:</p>
<pre class="brush: xml; gutter: true">login-processing-url=&quot;/perform_login&quot;</pre>
<p>A good reason to override this default URL is to hide the fact that the application is actually secured with Spring Security &#8211; that information should not be available externally.</p>
<h3><strong>4.3. The Landing page on Success</strong></h3>
<p>After a successful Login process, the user is redirected to a page &#8211; which by default is the root of the web application.</p>
<p>This can be overridden via the <em>default-target-url</em> attribute on <em>&lt;form-login&gt;</em>:</p>
<pre class="brush: xml; gutter: true">default-target-url=&quot;/homepage.html&quot;</pre>
<p>In case the <em>always-use-default-target</em> is set to true, then the user is always redirected to this page. If that attribute is set to false, then the user will be redirected to the previous page they wanted to visit before being promoted to authenticate.</p>
<h3><strong>4.3. The Landing page on Failure<br />
</strong></h3>
<p>Same as with the Login Page, the Login Failure Page is autogenerated by Spring Security at <em>/spring_security_login?login_error</em> by default.</p>
<p>This can be overridden via the <strong><em>authentication-failure-url</em> attribute</strong> on <em>&lt;form-login&gt;</em>:</p>
<pre class="brush: xml; gutter: true">authentication-failure-url=&quot;/login.html?error=true&quot;</pre>
<h2 id="conclusion"><strong>5. Conclusion</strong></h2>
<p>In this <strong>Spring Login Example</strong> we configured a simple authentication process &#8211; we discussed the Spring Security Login Form, the Security XML Configuration and some of the more advanced customizations available in the namespace.</p>
<p>The implementation of this Spring Login tutorial can be found in <a title="Spring MVC Tutorial" href="https://github.com/eugenp/tutorials" target="_blank">the github project</a> &#8211; this is an Eclipse based project, so it should be easy to import and run as it is.</p>
<p>When the project runs locally, the sample html can be accessed at:</p>
<p><a title="Login for Spring Security" href="http://localhost:8080/spring-security-login/login.html" target="_blank">http://localhost:8080/spring-security-login/login.html</a></p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/a8q7_QMcvYI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-security-login/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-security-login?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-security-login</feedburner:origLink></item>
		<item>
		<title>Spring MVC Tutorial</title>
		<link>http://feedproxy.google.com/~r/Baeldung/~3/OTcrNvZYeqo/spring-mvc-tutorial</link>
		<comments>http://www.baeldung.com/spring-mvc-tutorial#comments</comments>
		<pubDate>Tue, 30 Apr 2013 10:01:32 +0000</pubDate>
		<dc:creator>Eugen Paraschiv</dc:creator>
				<category><![CDATA[Spring]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[spring mvc]]></category>

		<guid isPermaLink="false">http://www.baeldung.com/?p=1949</guid>
		<description><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/519949ffecb2a1427e00e2fd"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div>Spring MVC Tutorial - simple example of a Spring MVC project, Java based Configuration]]></description>
				<content:encoded><![CDATA[<div align="center"><div style="width: 130px; height: 100px;"><a href="https://engine.influads.com/click/51994a00ecb2a11c64007d00"><img src="https://c212206.ssl.cf1.rackcdn.com/130x100.jpg" width="130" height="100" /><br/>Quality-only Ad Network. Simple!</a><br /><a href="http://influads.com">Powered by InfluAds</a></div></div><h2 id="overview"><strong>1. Overview and Maven<br />
</strong></h2>
<p>This is a simple <strong>Spring MVC tutorial</strong> showing how to set up a Spring MVC project, both with Java based Configuration as well as with XML Configuration.</p>
<p>The Maven dependencies for Spring MVC project are described in the in detail in the <a title="Spring with Maven" href="http://www.baeldung.com/spring-with-maven#mvc">Spring with Maven</a> article.</p>
<h2 id="webxml"><strong>2. The <em>web.xml</em></strong></h2>
<p>This is a simple configuration of the <em>web.xml</em> for a Spring MVC project:<br />

<pre class="brush: xml; gutter: true">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
   xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; 
   xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;
   xsi:schemaLocation=&quot;
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot; 
   id=&quot;WebApp_ID&quot; version=&quot;3.0&quot;&gt;

   &lt;display-name&gt;Spring MVC Java Config App&lt;/display-name&gt;

   &lt;servlet&gt;
      &lt;servlet-name&gt;mvc&lt;/servlet-name&gt;
      &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
      &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
   &lt;/servlet&gt;
   &lt;servlet-mapping&gt;
      &lt;servlet-name&gt;mvc&lt;/servlet-name&gt;
      &lt;url-pattern&gt;/&lt;/url-pattern&gt;
   &lt;/servlet-mapping&gt;

   &lt;context-param&gt;
      &lt;param-name&gt;contextClass&lt;/param-name&gt;
      &lt;param-value&gt;
         org.springframework.web.context.support.AnnotationConfigWebApplicationContext
      &lt;/param-value&gt;
   &lt;/context-param&gt;
   &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;org.baeldung.spring.web.config&lt;/param-value&gt;
   &lt;/context-param&gt;
   &lt;listener&gt;
      &lt;listener-class&gt;
         org.springframework.web.context.ContextLoaderListener
      &lt;/listener-class&gt;
   &lt;/listener&gt;

&lt;/web-app&gt;</pre>
</p>
<p>We are using <strong>Java based Configuration</strong>, so we&#8217;re using <em>AnnotationConfigWebApplicationContext</em> as the main context class &#8211; this accepts <em>@Configuration</em> annotated classes as input. As such, we only need to specify the package where these configuration classes are located, via <em>contextConfigLocation</em>.</p>
<p>To keep this mechanism flexible, multiple packages are also configurable here, simply space delimited:</p>
<pre class="brush: xml; gutter: true">   &lt;context-param&gt;
      &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
      &lt;param-value&gt;org.baeldung.spring.web.config org.baeldung.spring.persistence.config&lt;/param-value&gt;
   &lt;/context-param&gt;</pre>
<p>This allows more complex projects with multiple modules to manage their own Spring Configuration classes and contribute them to the overall Spring context at runtime.</p>
<p>Finally, the Servlet is mapped to <em>/</em> &#8211; meaning it becomes the <strong>default Servlet</strong> of the application and it will pick up every pattern that doesn&#8217;t have another exact match defined by another Servlet.</p>
<h2 id="configviews"><strong>3. The View Configuration<br />
</strong></h2>
<p>The Spring MVC Java configuration is simple &#8211; it uses the MVC configuration support introduced in Spring 3.1:</p>
<pre class="brush: java; gutter: true">@EnableWebMvc
@Configuration
public class ClientWebConfig extends WebMvcConfigurerAdapter {

   @Override
   public void addViewControllers(ViewControllerRegistry registry) {
      super.addViewControllers(registry);

      registry.addViewController(&quot;/sample.html&quot;);
   }

   @Bean
   public ViewResolver viewResolver() {
      InternalResourceViewResolver bean = new InternalResourceViewResolver();

      bean.setViewClass(JstlView.class);
      bean.setPrefix(&quot;/WEB-INF/view/&quot;);
      bean.setSuffix(&quot;.jsp&quot;);

      return bean;
   }
}</pre>
<p>Very important here is that we can register view controllers that create a direct mapping between the URL and the view name &#8211; <strong>no need for any Controller</strong> between the two now that we&#8217;re using Java configuration.</p>
<h2 id="jsp"><strong>4. The JSP Views</strong></h2>
<p>We defined above a basic view controller &#8211; <em>sample.html</em> &#8211; the corresponding jsp resource is:</p>
<pre class="brush: xml; gutter: true">&lt;html&gt;
   &lt;head&gt;&lt;/head&gt;

   &lt;body&gt;
      &lt;h1&gt;This is the body of the sample view&lt;/h1&gt;	
   &lt;/body&gt;
&lt;/html&gt;</pre>
<p>The JSP based view files are located under the /<em>WEB-INF</em> folder of the project, so they&#8217;re only accessible to the Spring infrastructure and not by direct URL access.</p>
<h2 id="conclusion"><strong>5. Conclusion</strong></h2>
<p>In this example we configured a simple and functional Spring MVC project, using Java configuration.</p>
<p>The implementation of this simple Spring MVC tutorial can be found in <a title="Spring MVC Tutorial" href="https://github.com/eugenp/tutorials" target="_blank">the github project</a> &#8211; this is an Eclipse based project, so it should be easy to import and run as it is.</p>
<p>When the project runs locally, the <em>sample.html</em> can be accessed at:</p>
<p><a title="Sample View on localhost" href="http://localhost:8080/spring-mvc/sample.html" target="_blank">http://localhost:8080/spring-mvc/sample.html</a></p>
<!-- Start Shortcoder content --><b><br>P.S. If you read this far, you should <a title="http://twitter.com/baeldung" href="http://twitter.com/baeldung" onclick="javascript:_gaq.push(['_trackEvent','twitter','twitter-page']);" target="_blank">follow me on Twitter</a>.<br><br> </b><!-- End Shortcoder content -->
<img src="http://feeds.feedburner.com/~r/Baeldung/~4/OTcrNvZYeqo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.baeldung.com/spring-mvc-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.baeldung.com/spring-mvc-tutorial?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=spring-mvc-tutorial</feedburner:origLink></item>
	</channel>
</rss>
