<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Spring Framework</title>
	<atom:link href="http://www.javabeat.net/category/spring-framework/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Mon, 13 May 2013 20:10:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Annotation Support for Scheduling and Asynchronous Execution</title>
		<link>http://www.javabeat.net/2013/05/annotation-scheduling-asynchronous-spring-examples/</link>
		<comments>http://www.javabeat.net/2013/05/annotation-scheduling-asynchronous-spring-examples/#comments</comments>
		<pubDate>Wed, 08 May 2013 16:04:02 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7284</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In the previous post Task Execution and Scheduling in Spring, I explained basic interfaces for task execution and scheduling. In this post I shall demonstrate an example for the same using annotations @Scheduled and @Async. Let us have working Eclipse IDE in place and follow the steps to create a scheduled Spring application: Create a project: [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>In the previous post <a href="http://www.javabeat.net/2013/05/task-execution-scheduling-spring/">Task Execution and Scheduling in Spring</a>, I explained basic interfaces for task execution and scheduling. In this post I shall demonstrate an example for the same using annotations <strong>@Scheduled</strong> and <strong>@Async</strong>. Let us have working Eclipse IDE in place and follow the steps to create a scheduled Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringScheduler</i> and create a package <i>com.javabeat</i> under the src directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>. Along with these libraries also add <i>aopalliance-1.0.jar</i> to the build path.</li>
<li><b>Create source files</b>: Create Java classes SchedulerSample,TaskSample and MainApp under the <i>com.javabeat</i> package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file Beans.xml under <i>src</i> directory.</li>
</ol>
<p>follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a></li>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<p>The content of <b>SchedulerSample.java</b> file are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerSample {

	  @Autowired
	  private TaskSample task;

	  @Scheduled(fixedDelay = 3000)
	  public void processScheduledJob() {
	    task.execute();
	  }

	  public TaskSample getTask() {
	    return task;
	  }

	  public void setTask(TaskSample task) {
	    this.task = task;
	  }
}
</pre>
<p>Here you can note that we have scheduled the task for a time of 3000 milliseconds.</p>
<p>The content of <b>TaskSample.java</b> file are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class TaskSample {
	@Async
	public void execute() {
		System.out
		.println(&quot;Executing asynchronous task for every fixedDelay of 3000millisecond.&quot;);
	}
}
</pre>
<p>The execute() method will be called every 3000 milliseconds.</p>
<p>The content of <b>Beans.xml</b> file are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
&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;
 xmlns:task=&quot;http://www.springframework.org/schema/task&quot;
 xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

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


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


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


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


http://www.springframework.org/schema/context/spring-context-3.0.xsd&quot;&gt;

&lt;context:component-scan base-package=&quot;com.javabeat&quot; /&gt;

&lt;task:annotation-driven executor=&quot;executor&quot; scheduler=&quot;scheduler&quot; /&gt;

&lt;task:executor id=&quot;executor&quot; pool-size=&quot;5&quot; /&gt;

&lt;task:scheduler id=&quot;scheduler&quot; pool-size=&quot;5&quot; /&gt;

&lt;/beans&gt;
</pre>
<p>Here we need to note few things:</p>
<ul>
<li>To enable the annotation driven scheduling we have added the <i>annotation-driven</i> element from the task namespace.</li>
<li>Schema http://www.springframework.org/schema/task, http://www.springframework.org/schema/task/spring-task-3.0.xsd, are added to the above file.</li>
<li><i>task:executor </i> &#8211; creates an instance of ThreadPoolTaskExecutor.</li>
<li><i>task:scheduler </i> &#8211; creates an instance of ThreadPoolTaskScheduler.</li>
</ul>
<p>To execute the application the <b>MainApp.java</b> is as follows:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {
	    new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);
	  }
}
</pre>
<p><b>Execute the code</b></p>
<p>The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
Executing asynchronous task for every fixedDelay of 3000millisecond.
Executing asynchronous task for every fixedDelay of 3000millisecond.
</pre>
<p>As you can see the message is printed at a delay of 3000millisecond. You need to stop the application to stop the printing of message.</p>
<h2>Summary</h2>
<p>In this section I demonstrated an example of scheduling the Spring application using the annotation.If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fspring-framework%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/spring-framework/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/spring-framework/feed/" data-count="vertical" data-text="Spring Framework" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/05/annotation-scheduling-asynchronous-spring-examples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Task Execution and Scheduling in Spring</title>
		<link>http://www.javabeat.net/2013/05/task-execution-scheduling-spring/</link>
		<comments>http://www.javabeat.net/2013/05/task-execution-scheduling-spring/#comments</comments>
		<pubDate>Wed, 08 May 2013 09:50:07 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7242</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Spring 2.0 introduced abstractions for asynchronous execution and scheduling of tasks. The key interfaces for scheduling and task execution are as listed as TaskExecutor, TaskScheduler, Trigger, TriggerContext and ScheduledFuture. Let take a look at each of these interfaces. This article explores spring&#8217;s scheduler related APIs in detail. You can read the official explanation for this API&#8217;s here. follow us on @twitter and @facebook Spring [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Spring 2.0 introduced abstractions for asynchronous execution and scheduling of tasks. The key interfaces for scheduling and task execution are as listed as <strong>TaskExecutor, </strong><strong>TaskScheduler, </strong><strong>Trigger, </strong><strong>TriggerContext and </strong><strong>ScheduledFuture</strong>. Let take a look at each of these interfaces. This article explores spring&#8217;s scheduler related APIs in detail. You can read the official explanation for this API&#8217;s <a href="http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html" target="_blank">here</a>.</p>
<p>follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/spring-framework-books/">Spring Framework Books</a></li>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>TaskExecutor</h2>
<p>TaskExecutor was introduced as an abstraction for dealing with executors. <i>Executors</i> are the Java 5 name for the concept of thread pools. The primary aim of TaskExecutor is to abstract away the need for Java 5 when using thread pools. The interface has only a single method as shown below:</p>
<pre class="brush: java; title: ; notranslate">
public interface TaskExecutor extends java.util.concurrent.Executor {
void execute(Runnable task);
}
</pre>
<p><b>TaskExecutor Implementation Classes</b></p>
<ul>
<li>SimpleAsyncTaskExecutor: Does not reuse threads. It starts a new thread and is asynchronus.</li>
<li>SyncTaskExecutor: No thread reuse and is synchonous. Instead, each invocation takes place in the calling thread.</li>
<li>ConcurrentTaskExecutor: Exposes the Java 5 <i>java.util.concurrent.Executor</i>.</li>
<li>SimpleThreadPoolTaskExecutor: It is a subclass of Quartz&#8217;s SimpleThreadPool which listens to Spring&#8217;s lifecycle callbacks.</li>
<li>ThreadPoolTaskExecutor: It exposes bean properties for configuring a ThreadPoolExecutor configuration and and wraps it in a TaskExecutor.</li>
<li>TimerTaskExecutor: This implementation uses a single TimerTask as its backing implementation. It&#8217;s different from the SyncTaskExecutor in that the method invocations are executed in a separate thread, although they are synchronous in that thread.</li>
<li>WorkManagerTaskExecutor: This implementation uses the CommonJ WorkManager as its backing implementation</li>
</ul>
<h2>TaskScheduler</h2>
<p>This interface has a variety of methods for scheduling tasks to run at some point in the future, as seen below:</p>
<pre class="brush: java; title: ; notranslate">
public interface TaskScheduler {
ScheduledFuture schedule(Runnable task, Trigger trigger);

    ScheduledFuture schedule(Runnable task, Date startTime);

    ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period);

    ScheduledFuture scheduleAtFixedRate(Runnable task, long period);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay);

    ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay);
}
</pre>
<p>FixedRate &#8211; period will be measured from the start time<br />
FixedDelay &#8211; period will be measured from the completion time</p>
<p><b>TaskScheduler Implementation Classes</b></p>
<ul>
<li>TimerManagerTaskScheduler: Delegates to a CommonJ TimerManager instance, typically configured with a JNDI-lookup.</li>
<li>ThreadPoolTaskScheduler: Used whenever external thread management is not a requirement. Internally, it delegates to a ScheduledExecutorService instance.</li>
</ul>
<h2>Trigger</h2>
<p>Using Trigger the execution times may be determined based on past execution outcomes or even arbitrary conditions. The Trigger interface is as follows:</p>
<pre class="brush: java; title: ; notranslate">
public interface Trigger {
Date nextExecutionTime(TriggerContext triggerContext);
}
</pre>
<p>TriggerContext is an interface and encapsulates all of the relevant data.</p>
<p><b>Trigger Implementation Classes</b></p>
<ul>
<li>CronTrigger: It enables the scheduling of tasks based on cron expressions.</li>
<li>PeriodicTrigger: It accepts a fixed period, an optional initial delay value, and a boolean to indicate whether the period should be interpreted as a fixed-rate or a fixed-delay.</li>
</ul>
<h2>Bootstrapping the scheduler</h2>
<p>Since Spring 3.0, XML namespace for configuring TaskExecutor and TaskScheduler instances is available. It also provides a convenient way to configure tasks to be scheduled with a trigger. Add the following schema to the spring configuration file(xml file):</p>
<pre class="brush: java; title: ; notranslate">

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


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

</pre>
<p><b>Task Namespace</b><br />
Add the following configuration :</p>
<pre class="brush: java; title: ; notranslate">
&lt;task:executor id=&quot;executor&quot; pool-size=&quot;8-25&quot; queue-capacity=&quot;100&quot; /&gt;
&lt;task:scheduler id=&quot;scheduler&quot; pool-size=&quot;10&quot; /&gt;
</pre>
<ul>
<li><b>task:executor </b> &#8211; Create instance of ThreadPoolTaskExecutor</li>
<li><b>task:scheduler </b> &#8211; Create instance of ThreadPoolTaskScheduler</li>
<li><b>pool-size</b> &#8211; If the value is not provided, then the default thread pool will only have a single thread.</li>
<li><b>queue-capacity</b> &#8211; Number of tasks held back. Default value is <i>Unbound</i></li>
<li><b>rejection-policy</b> &#8211; This another attribute not mentione the above example. Used for to throw exception when a task is rejected. Its default value is <i> AbortPolicy</i>. Other possbile values are &#8211; <i> DiscardPolicy </i>, <i>DiscardOldestPolicy </i>, and <i> CallerRunsPolicy</i>.</li>
</ul>
<h2>Scheduling the Tasks</h2>
<p>Tasks can be scheduled in the following three ways:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ol>
<li>Annotation Driven</li>
<li>XML Driven</li>
<li>Programmatically</li>
</ol>
<p><b>1. Annotation Driven </b></p>
<p>The @Scheduled annotation can be added to a method along with trigger metadata for task scheduling. The @Async annotation can be provided on a method so that invocation of that method will occur asynchronously.</p>
<p>Add following to your spring configuration file:</p>
<pre class="brush: java; title: ; notranslate">
&lt;context:component-scan annotation-config=&quot;true&quot; base-package=&quot;com.javabeat&quot;/&gt;
&lt;task:annotation-driven executor=&quot;executor&quot; scheduler=&quot;scheduler&quot; /&gt;
</pre>
<p>The following example will only execute on weekdays.:</p>
<pre class="brush: java; title: ; notranslate">
@Scheduled(cron=&quot;*/5 * * * * MON-FRI&quot;)
public void doSomeTask(){
 // some task that should execute on weekdays only
}
</pre>
<blockquote><p>Scheduled methods must have void returns and must not expect any arguments.</p></blockquote>
<p>Syntax for @Async annotation is:</p>
<pre class="brush: java; title: ; notranslate">
@Async
void doSomething() {
    // this will be executed asynchronously
}
</pre>
<p><b>2. XML Driven</b></p>
<p>Add the following configuration to the spring configuration file :</p>
<pre class="brush: java; title: ; notranslate">
&lt;task:scheduled-tasks scheduler=&quot;sampleScheduler&quot;&gt;
   &lt;task:scheduled ref=&quot;someObject&quot;
      method=&quot;someMethod&quot; fixed-delay=&quot;5000&quot;/&gt;
&lt;/task:scheduled-tasks&gt;
</pre>
<p><b>3. Programmatically </b></p>
<p>Go for programmatic way when your application desire more control on scheduling. For example :</p>
<pre class="brush: java; title: ; notranslate">

ThreadPoolTaskScheduler scheduler = (ThreadPoolTaskScheduler) appContext.getBean(&quot;scheduler&quot;);
CronTrigger trigger = new CronTrigger(&quot;*/5 * * * * MON-FRI&quot;);

ScheduledFuture&lt;Object&gt; scedulefuture= scheduler.schedule(taskObject, trigger );

</pre>
<p>In the above example instead of <i>schedule()</i> method, you can use <i>scheduleAtFixedRate(.. , ..)</i> or <i>scheduleWithFixedDelay(.. , ..)</i>.</p>
<h2>Summary</h2>
<p>In this post we saw the basics of task execution and scheduling in Spring. We studied the interfaces <b>TaskExecutor</b>, <b>TaskScheduler</b>, and <b>Trigger</b> and their implementation classes. We also saw methods of scheduling the tasks, annotation driven, XML driven and programmatically. In the next article I shall demonstrate this with an example. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/05/task-execution-scheduling-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cache Abstraction In Spring (Example for @Cacheable and @CacheEvict)</title>
		<link>http://www.javabeat.net/2013/05/cache-abstraction-spring-cacheable-cacheevict/</link>
		<comments>http://www.javabeat.net/2013/05/cache-abstraction-spring-cacheable-cacheevict/#comments</comments>
		<pubDate>Wed, 01 May 2013 13:39:20 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7147</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Since Spring 3 a new abstraction layer for caching services has been introduced called Cache Abstraction. The idea is to provide a set of common features, mainly annotations, to activate and manage the caches. Cache Abstraction is nothing but applying caching to Java methods, reducing thus the number of executions based on the information available in [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Since Spring 3 a new abstraction layer for caching services has been introduced called <b>Cache Abstraction</b>. The idea is to provide a set of common features, mainly annotations, to activate and manage the caches. <em>Cache Abstraction</em> is nothing but applying caching to Java methods, reducing thus the number of executions based on the information available in the cache. That is, each time a targeted method is invoked, the abstraction will apply a caching behavior checking whether the method has been already executed for the given arguments.</p>
<ul>
<li>If yes, then the cached result is returned without having to execute the actual method.</li>
<li>If no, then method is executed, the result cached and returned to the user so that, the next time the method is invoked, the cached result is returned.</li>
</ul>
<p>As the name implies, Cache Abstraction is not an actual implementation. Hence it requires the use of an actual storage to store the cache data. <i>Ehcache support</i> is provided out of the box. There is also an implementation based on <i>JDK’s ConcurrentMap</i> and you can actually plug-in different back-end caches.</p>
<p>follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>Annotation based Caching</h2>
<p>For caching declaration, the abstraction provides following Java annotations:</p>
<ul>
<li><b>@Cacheable</b>: put the method returned value(s) into the cache.</li>
<li><b>@CacheEvict</b>: remove an entry from the cache.</li>
<li><b>@CachePut</b>: force a cache entry to be updated.</li>
<li><b>@Caching</b>: @Caching allows multiple nested @Cacheable, @CachePut and @CacheEvict to be used on the same method.</li>
</ul>
<h2>Enable caching annotations</h2>
<p>Caching feature needs to be declaratively enabled by using either of following ways:</p>
<ul>
<li>Add the annotation @EnableCaching to one of your @Configuration classes.</li>
<li>Alternatively for XML configuration use the <i><b>cache:annotation-driven</b></i> element.</li>
</ul>
<h2>@Cacheable annotation</h2>
<p>In Spring <i>@Cacheable</i> is useful in the case when a very complex code is running for many times. <i>@Cacheable</i> caches the result per input values of methods, so on subsequent invocations (with the same arguments), the value in the cache is returned without having to actually execute the method. Spring handles this functionality by second level cache. @Cacheable is used in the code as shown below:</p>
<pre class="brush: java; title: ; notranslate">
@Cacheable(&quot;product&quot;)
public String getProduct(int productId){}
</pre>
<h2>@CacheEvict annotation</h2>
<p>The cache abstraction allows not just population of a cache store but also eviction i.e removes data from the cache. @CacheEvict in spring is used to evict cache value. @CacheEvict is applied on the method. This annotation has an extra parameter allEntries which indicates whether a cache-wide eviction needs to be performed rather then just an entry one (based on the key):</p>
<pre class="brush: java; title: ; notranslate">
@CacheEvict(value = &quot;product&quot;, allEntries=true)
public void setProduct(int productId){}
</pre>
<p>This option comes in handy when an entire cache region needs to be cleared out &#8211; rather then evicting each entry (which would take a long time since it is inefficient), all the entires are removed in one operation as shown above.</p>
<h2>Example for @Cacheable and @CacheEvict</h2>
<p>The following example demonstrates the use of the @Cacheable and @CacheEvict annotations and enabling them in the Spring application. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringCacheAbstraction</i> and create a package <i>com.javabeat</i> under the <i>src</i> directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>. Along with te specified JARs in the link, also add make sure these JARs are in the buildpath of the project:<i>aopalliance-x.0.jar</i>, <i>ehcache-x.x.0.jar</i>(you can download latest ehcache.jar from <a title="http://sourceforge.net/projects/ehcache/files/ehcache/ehcache-1.5.0/" href="http://sourceforge.net/projects/ehcache/files/ehcache/ehcache-1.5.0/" target="_blank">here</a>: )</li>
<li><b>Create source files</b>: Create Java classes <i>Product</i>,and <i>MainApp</i> under the com.javabeat package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file Beans.xml and ehcache.xml under <i>src</i> directory.</li>
</ol>
<p>Contents of <b>Product.java</b> are as below:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

public class Product {
	@CacheEvict(value = &quot;prod&quot;, allEntries = true)
	public void setProduct(int productId) {
		System.out.println(&quot;execute setProduct method..&quot;);
	}

	@Cacheable(&quot;prod&quot;)
	public String getProduct(int productId) {
		System.out.println(&quot;execute getProduct method..&quot;);
		if (productId == 1) {
			return &quot;Product A&quot;;
		} else {
			return &quot;Product B&quot;;
		}
	}
}
</pre>
<p>Contents of <b>MainApp.java</b> are as below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String... args) {
		AbstractApplicationContext context = new ClassPathXmlApplicationContext(
				&quot;Beans.xml&quot;);
		Product product = (Product) context.getBean(&quot;product&quot;);

		// calling getProduct method first time.
		System.out.println(product.getProduct(1));

		// calling getProduct method second time. This time, method will not
		// execute.
		System.out.println(product.getProduct(1));

		// calling setProduct method to evict the cache value
		product.setProduct(1);

		// calling getProduct method third time. This time, method will execute
		// again.
		System.out.println(product.getProduct(1));
	}
}
</pre>
<p>There is a method <i>getProduct</i> in the class Product. We have called it three times. First time <i>getProduct</i> methods runs and sets result in cache named <i>prod</i>. Second time <i>getProduct</i> does not run because there is value in cache. Now call <i>setProduct</i> to remove the cache value. Again run <i>getProduct</i> method . This method will run because cache value is empty because of eviction.</p>
<p>Contents of <b>Beans.xml</b> are as below:</p>
<pre class="brush: java; title: ; notranslate">
&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;
       xmlns:cache=&quot;http://www.springframework.org/schema/cache&quot;
       xmlns:p=&quot;http://www.springframework.org/schema/p&quot;
       xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans

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


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


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


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


http://www.springframework.org/schema/cache/spring-cache.xsd&quot;&gt;

&lt;cache:annotation-driven /&gt;

	&lt;bean id=&quot;product&quot; class=&quot;com.javabeat.Product&quot;&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;cacheManager&quot; class=&quot;org.springframework.cache.ehcache.EhCacheCacheManager&quot; p:cache-manager-ref=&quot;ehcache&quot;/&gt;
	&lt;bean id=&quot;ehcache&quot; class=&quot;org.springframework.cache.ehcache.EhCacheManagerFactoryBean&quot; p:config-location=&quot;classpath:ehcache.xml&quot;/&gt;

&lt;/beans&gt;
</pre>
<p>To get @Cacheable our result we have to configure org.springframework.cache.ehcache.EhCacheCacheManager in Beans xml as seen above. All second level configuration properties are configured in an ehcache.xml and that xml file is configured in Beans.xml as seen above.</p>
<p>Contents of <b>ehcache.xml</b> are as below:</p>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;ehcache xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:noNamespaceSchemaLocation=&quot;http://ehcache.org/ehcache.xsd&quot;&gt;
	&lt;defaultCache eternal=&quot;true&quot; maxElementsInMemory=&quot;100&quot;
		overflowToDisk=&quot;false&quot; /&gt;
	&lt;cache name=&quot;prod&quot; maxElementsInMemory=&quot;10000&quot; eternal=&quot;true&quot;
		overflowToDisk=&quot;false&quot; /&gt;
&lt;/ehcache&gt;
</pre>
<p>Cache name has been declared as which is used in the Product.java class for caching result of the method.</p>
<h2>Execute</h2>
<p>Once all the code is ready, execute the MainApp class and if everythingis fine, the following output should appear on the console:</p>
<pre class="brush: java; title: ; notranslate">
execute getProduct method..
Product A
Product A
execute setProduct method..
execute getProduct method..
Product A
</pre>
<h2>Summary</h2>
<p>In this post we saw the basics of Cache Abstraction in Spring. An example is used to demostrate the use of @Cacheable and @CacheEvict. In the next post I shall cover some other feature of the Spring. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.  follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook<br />
</a></p>
<ul>
<li style="display: inline !important;"></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/05/cache-abstraction-spring-cacheable-cacheevict/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resources API in Spring &#8211; Part 2 (ResourceLoaderAware)</title>
		<link>http://www.javabeat.net/2013/04/resources-api-spring-resourceloaderaware/</link>
		<comments>http://www.javabeat.net/2013/04/resources-api-spring-resourceloaderaware/#comments</comments>
		<pubDate>Mon, 29 Apr 2013 00:37:19 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7124</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In the previous post I discussed about the external resource loading in Spring using Resource Loader interface, and setter methods. In this post I shall discuss about another form of resource loading through ResourceLoaderAware interface. Prior to release of Spring 2.5, this technique was used to load the external resources. Post Spring 2.5, you can [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In the previous post I discussed about the <a href="http://www.javabeat.net/2013/04/resources-api-spring/">external resource loading in Spring using Resource Loader interface</a>, and setter methods. In this post I shall discuss about another form of resource loading through <em>ResourceLoaderAware </em>interface. Prior to release of Spring 2.5, this technique was used to load the external resources. Post Spring 2.5, you can rely upon <em>autowiring </em>of the <em>ResourceLoader </em>as an alternative to implementing the <em>ResourceLoaderAware </em>interface.</p>
<p><span style="color: #000080;"><strong>The <i>ResourceLoaderAware</i> interface is a special marker interface, identifying objects that expect to be provided with a ResourceLoader reference.</strong></span></p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>Example for Using ResourceLoaderAware</h2>
<p>The example below demonstrates the use of ResourceLoaderAware to load the external resources. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringExternalResourceExample</i> and create a package <i>com.javabeat</i> under the <i>src</i> directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create configuration file</b>: Create XML based configuration file Beans.xml under <i>src</i> directory.</li>
<li><b>Create source files</b>: Create Java classes MainApp and ProductService under the com.javabeat package.</li>
</ol>
<p>Contents of <b>ProductService.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class ProductService implements ResourceLoaderAware {

	private ResourceLoader resourceLoader;

	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	public Resource getResource(String location) {
		return resourceLoader.getResource(location);
	}
}
</pre>
<p>Contents of <b>Beans.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
&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:aop=&quot;http://www.springframework.org/schema/aop&quot;
         xmlns:tx=&quot;http://www.springframework.org/schema/tx&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-2.5.xsd


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


http://www.springframework.org/schema/tx/spring-tx-2.5.xsd


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


http://www.springframework.org/schema/aop/spring-aop-2.5.xsd


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


http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;

      &lt;bean id=&quot;productService&quot; class=&quot;com.javabeat.ProductService&quot; &gt;
      &lt;/bean&gt;

    &lt;/beans&gt;
</pre>
<p>Contents of <b>MainApp.java</b> are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class MainApp {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);
		ProductService productService = (ProductService) ctx
				.getBean(&quot;productService&quot;);

		try {
			Resource resource = productService
					.getResource(&quot;file:c:\\SampleResourceFile.txt&quot;);
			InputStream is = resource.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
</pre>
<p>We get the resource from the bean productService.</p>
<p>Now execute the code and the following output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
**********************************
HI I'M AN EXTERNAL RESOURCE FILE
**********************************
</pre>
<h2>Constructing application contexts</h2>
<p>ApplicationContext is an interface only. You have to instantiate an implementation of it. An application context constructor (for a specific application context type) generally takes a string or array of strings as the location path(s) of the resource(s) such as XML files that make up the definition of the context. For example:</p>
<pre class="brush: java; title: ; notranslate">
ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;com/javabeat/beans.xml&quot;);
</pre>
<p>The <i>ClassPathXmlApplicationContext</i> implementation builds an application context by loading an XML<br />
configuration file from the classpath, when the location path doesn&#8217;t have a prefix. Besides <i>ClassPathXmlApplicationContext</i>, several other ApplicationContext implementations are provided by Spring. <i>FileSystemXmlApplicationContext</i> is used to load XML configuration files from the file system or from URLs, while <i>XmlWebApplicationContext</i> and <i>XmlPortletApplicationContext</i> can be used in web and portal applications only.</p>
<h2>The classpath*: prefix</h2>
<p>When constructing an XML-based application context, a location string may use the special classpath &#8220;*:&#8221; prefix: An example:</p>
<pre class="brush: java; title: ; notranslate">
ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;classpath*:conf/appContext.xml&quot;);
</pre>
<p>The <b>classpath*:conf/appContext.xml</b> simply means that all appContext.xml files under conf folders in all your jars on the classpath will be picked up and joined into one big application context.</p>
<h2>Summary</h2>
<p>In this post we saw how to load resources using <i>ResourceLoaderAware</i> interface. We also saw how to construct the application contexts and use wild card in application context constructor using the <i>classpath*:</i> prefix.Please refer <a href="http://static.springsource.org/spring/docs/2.5.6/reference/resources.html" target="_blank">here</a> for the official documentation on resource API. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/resources-api-spring-resourceloaderaware/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Resources API in Spring &#8211; Part 1</title>
		<link>http://www.javabeat.net/2013/04/resources-api-spring/</link>
		<comments>http://www.javabeat.net/2013/04/resources-api-spring/#comments</comments>
		<pubDate>Sun, 28 Apr 2013 16:19:12 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7097</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>At times we may need to read external resources (e.g., text files, XML files, properties file, or image files) into our application. These resources can be located different locations (e.g., a file system, classpath, or URL). Usually, you have to deal with different APIs for loading resources from different locations. To handle such file accessing [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>At times we may need to read external resources (e.g., text files, XML files, properties file, or image files) into our application. These resources can be located different locations (e.g., a file system, classpath, or URL). Usually, you have to deal with different APIs for loading resources from different locations. To handle such file accessing tasks, Spring provides an <i>interface</i> called as <b>Resource</b> contained in the package <i>org.springframework.core.io</i>. In this post I shall cover the details of Resource interface, loading of Resource using <i>getResource()</i> method, using Resource loader and through setter methods.</p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>Resource Interface</h2>
<p>Contents of this interface are as shown below:</p>
<pre class="brush: java; title: ; notranslate">
public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isOpen();

    URL getURL() throws IOException;

    File getFile() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();
}
</pre>
<p>Contents of <strong>InputStreamSource </strong>are as below:</p>
<pre class="brush: java; title: ; notranslate">
public interface InputStreamSource {

    InputStream getInputStream() throws IOException;
}
</pre>
<p><i>Resource</i> is a general interface in Spring for representing an external resource.</p>
<h2>Spring Built-in implementations for Resource interface</h2>
<p>Spring provides several built-in implementations for the <i>Resource</i> interface as listed below:</p>
<ol>
<li><b>UrlResource</b>: Represents a URL.</li>
<li><b>ClassPathResource</b>: Represents a File loaded from the classpath.</li>
<li><b>FileSystemResource</b>: Represents a File.</li>
<li><b>ServletContextResource</b>: This implementation is for <i>ServletContext</i> resources, interpreting relative paths within the relevant web application&#8217;s root directory.</li>
<li><b>InputStreamResource</b>: Represents an input stream.</li>
<li><b>ByteArrayResource</b>: TRepresents a byte array.</li>
</ol>
<h2>Resource API Example</h2>
<p>The example below demonstrates the use of Resource interface. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringExternalResourceExample</i> and create a package <i>com.javabeat</i> under the <i>src</i> directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create source files</b>: Create Java classe <em>MainApp </em>under the <em>com.javabeat</em> package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file <em>Beans.xml</em> under <i>src</i> directory.</li>
</ol>
<p>Contents of <b>MainApp.java</b> are as below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class MainApp {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);

		Resource resource = ctx.getResource(&quot;file:c:\\SampleResourceFile.txt&quot;);
		try {
			InputStream is = resource.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
</pre>
<p>Note that we have used the <i>getResource()</i> to load a text file from File system. Suppose say you have the text file from URL path then the code would be as below:</p>
<pre class="brush: java; title: ; notranslate">
Resource resource =  ctx.getResource(&quot;url:http://www.exampledomain.com/SampleResourceFile.txt&quot;);
</pre>
<p>If you want to load the the text file from the classpath then the line of code would be as below:</p>
<pre class="brush: java; title: ; notranslate">
Resource resource = ctx.getResource(&quot;classpath:com/javabeat/SampleResourceFile.txt&quot;);
</pre>
<p>The contents of the <b>Beans.xml</b> are as below:</p>
<pre class="brush: java; title: ; notranslate">
&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-2.5.xsd&quot;&gt;

&lt;/beans&gt;
</pre>
<p>The <b>SampleResourceFile.txt</b> contains the following text:</p>
<pre class="brush: java; title: ; notranslate">
**********************************
HI I'M AN EXTERNAL RESOURCE FILE
**********************************
</pre>
<p>This is a standalone application and does not need the Spring container. Now execute the above code then the output would be as below:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
**********************************
HI I'M AN EXTERNAL RESOURCE FILE
**********************************
</pre>
<h2>Injecting Resources</h2>
<p>Now let&#8217;s say you want to have a reference of the resource which you may use in your application; this can be achieved in two ways:</p>
<ul>
<li><b>Resource Injection: </b>By using setter method.</li>
<li><b>Using ResourceLoader</b>: Here we use ResourceLoader interface to help us get an instance of the resource we require. Such technique is used for loading dynamic resources i.e which will be loaded based on some business logic.</li>
</ul>
<h2>Example for Resource Injection</h2>
<p>Setup the project as in the example above:<br />
Contents of <b>ProjectService.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.core.io.Resource;

public class ProductService {

	private Resource externalResource;

	public Resource getExternalResource() {
		return externalResource;
	}

	public void setExternalResource(Resource externalResource) {
		this.externalResource = externalResource;
	}
}
</pre>
<p>In the above class, I&#8217;ve created a property of type Resource.</p>
<p>Contents of <b>MainApp.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class MainApp {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);
		ProductService productService = (ProductService) ctx
				.getBean(&quot;productService&quot;);

		try {
			Resource resource = productService.getExternalResource();
			InputStream is = resource.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
</pre>
<p>In the above test class, we get the bean in the usual way and when you get the <em>externalResource </em>property from this bean, you can successfully read the information from this resource object.<br />
Contents of <b>Beans.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
   &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:aop=&quot;http://www.springframework.org/schema/aop&quot;
            xmlns:tx=&quot;http://www.springframework.org/schema/tx&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-2.5.xsd


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


http://www.springframework.org/schema/tx/spring-tx-2.5.xsd


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


http://www.springframework.org/schema/aop/spring-aop-2.5.xsd


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


http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;

         &lt;bean id=&quot;productService&quot; class=&quot;com.javabeat.ProductService&quot; &gt;
         &lt;property name=&quot;externalResource&quot; value=&quot;file:c:\\SampleResourceFile.txt&quot;&gt;&lt;/property&gt;
         &lt;/bean&gt;

    &lt;/beans&gt;
</pre>
<p>In the above <em>Beans.xml</em> file I&#8217;ve have injected the property with the path of the file we want spring to provide us with.<br />
Executing the above code gives the below output :</p>
<pre class="brush: java; title: ; notranslate">
**********************************
HI I'M AN EXTERNAL RESOURCE FILE
**********************************
</pre>
<h2>Example for ResourceLoader</h2>
<p>Setup the project as in the example above:<br />
Contents of <b>ProjectService.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

public class ProductService {

	@Autowired
	private ResourceLoader resourceLoader;

	public Resource getResource(String location) {
		return resourceLoader.getResource(location);
	}
}
</pre>
<p>The above class has a property type <em>ResourceLoader</em>. <em>ResourceLoader </em>is used to dynamically load the resource. To tell the spring about injecting value into this, we have used the <i>@Autowired</i> annotation. With annotations, we need not create setter methods for our properties. Only thing we have to do is to tell Spring framework that we are using the annotation, so in addition to the injecting values based on the property tags from the xml, it has to read class level annotations also. We do this by adding <i> </i>in the Beans.xml file.</p>
<p>Contents of <b>MainApp.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;

public class MainApp {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(&quot;Beans.xml&quot;);
		ProductService productService = (ProductService) ctx
				.getBean(&quot;productService&quot;);

		Resource resource = productService
				.getResource(&quot;file:c:\\SampleResourceFile.txt&quot;);
		try {
			InputStream is = resource.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
</pre>
<p>Contents of <b>Beans.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
    &lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
         xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot;
         xmlns:tx=&quot;http://www.springframework.org/schema/tx&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-2.5.xsd


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


http://www.springframework.org/schema/tx/spring-tx-2.5.xsd


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


http://www.springframework.org/schema/aop/spring-aop-2.5.xsd


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


http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;

              &lt;context:annotation-config /&gt;
      &lt;bean id=&quot;productService&quot; class=&quot;com.javabeat.ProductService&quot; /&gt;

    &lt;/beans&gt;
</pre>
<p>Executing the above code gives the below output :</p>
<pre class="brush: java; title: ; notranslate">
**********************************
HI I'M AN EXTERNAL RESOURCE FILE
**********************************
</pre>
<h2>Summary</h2>
<p>In this post I discussed about the external resource injection in Spring applications. This is part-1 of the series, in the next post I shall cover another feature ResourceLoaderAware interface, Resources as dependencies and Application contexts and Resource paths. Please refer <a href="http://static.springsource.org/spring/docs/2.5.6/reference/resources.html" target="_blank">here</a> for the official documentation on resource API.  If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/resources-api-spring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>New Features in Spring 3.1</title>
		<link>http://www.javabeat.net/2013/04/new-features-spring-3-1/</link>
		<comments>http://www.javabeat.net/2013/04/new-features-spring-3-1/#comments</comments>
		<pubDate>Thu, 25 Apr 2013 14:31:07 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7074</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This post will feature some of the major features and enhancements of Spring 3.1. Released in the year 2011, Spring 3.1 introduced many new exciting features as listed and described in this article. This article would provide very good idea on the new features introduced and how it is different from the previous versions. If [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>This post will feature some of the major features and enhancements of Spring 3.1. Released in the year 2011, Spring 3.1 introduced many new exciting features as listed and described in this article. This article would provide very good idea on the new features introduced and how it is different from the previous versions. If you are developer who are interested in choosing the spring version, this article would be very useful.</p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
<li></li>
</ul>
<h2>Cache Abstraction</h2>
<p>Spring 3.1 has introduced a new feature called <strong>Cache Abstraction</strong>. Through this feature Spring can add caching concept to any existing application with very few changes in the code. Some of the features of Cache abstraction are:</p>
<ul>
<li>Declarative caching for Spring applications, which means minimal impact on code and we can plug in various caching solutions to the existing applications.</li>
<li>This feature is not an implementation, but an abstraction.</li>
<li>This feature frees you from writing logic, but does not provide stores. Cache abstraction provides integration with two storage&#8217;s &#8211; one on top of the <strong>JDK ConcurrentMap</strong> and one for <strong><em>ehcache </em>library</strong>.</li>
<li>Key annotations are <b>@Cacheable</b> and <b>@CacheEvict</b>.</li>
<li>You can use Spring EL for <i>key</i> and <i>condition</i> attributes</li>
<li>Annotations triggered by <b>&lt;cache:annotation-driven/&gt;</b>.</li>
</ul>
<h2>Environment Abstraction</h2>
<p>Injectable environment abstraction API, <i>org.springframework.core.env.Environment</i>, has been integrated throughout the spring container. This has two core concepts:</p>
<ul>
<li>Bean Profile</li>
<li>Property Source</li>
</ul>
<p>These explained in the next sections. Spring&#8217;s Environment abstraction provides a single location to configure both profiles and properties.</p>
<h2>Bean Definition Profiles</h2>
<p>Bean definition profiles represent a general-purpose way that allows for registration of different beans in different environments. i.e it determines which bean definitions should be registered for a given deployment context. Some of the features of Bean Definition Profiles are:</p>
<ul>
<li>As mentioned above , this feature helps logical grouping of bean definitions, for e.g., dev, staging, prod</li>
<li>Configuration of XML is done via <b></b>. Java-based configuration is done via <b>@Profile</b>.</li>
<li>Activation of profiles can be done programmatically, using servlet init-params in web.xml, through system property, in tests via @ActiveProfiles.</li>
</ul>
<h2>PropertySource Abstraction</h2>
<p>As mentioned above, Spring&#8217;s Environment abstraction provides search operations over a configurable hierarchy of property sources.<br />
A <i>PropertySource</i> is a simple abstraction over any source of key-value pairs. E.g:property files, system properties,<br />
servlet context, JNDI, etc.</p>
<p>Spring&#8217;s <i>DefaultEnvironment</i> is configured with two <em>PropertySource</em> objects</p>
<ol>
<li>one representing the set of JVM system properties (<em>System.getProperties()</em>)</li>
<li>one representing the set of system environment variables (System.getenv())</li>
</ol>
<h2>Code equivalents for Spring&#8217;s XML namespaces</h2>
<p>Spring XML namespace elements like <i>&lt;context:component-scan/&gt;</i>, <i>&lt;tx:annotation-driven/&gt;</i> and <i>&lt;mvc:annotation-driven&gt;</i>, have code-based equivalents since Spring 3.1 most in the form of <i>@Enable</i> annotations. These work in conjunction with the Spring&#8217;s <i>@Configuration</i> classes.</p>
<p><strong>@Enable Annotations</strong>:</p>
<ul>
<li>Applied at the class-level on <em>@Configuration</em> classes</li>
<li>Roughly equivalent to their XML namespace counterparts</li>
<li>Annotations available in Spring 3.1 are: @EnableTransactionManagement, @EnableAsync, @EnableScheduling, @EnableLoadTimeWeaving, @EnableWebMvc, @EnableCaching, @EnableAspectJAutoProxy, @EnableLoadTimeWeaving, @EnableSpringConfigured</li>
</ul>
<h2>Support for Hibernate 4.x</h2>
<p>Spring 3.1, support Hibernate 4.x, natively and through JPA. Native support is through a dedicated <i>org.springframework.orm.hibernate4</i> package, dealing with package rearrangements in the Hibernate API. It also presers the compatibility with Hibernate 3.2.</p>
<h2>TestContext framework support for @Configuration classes and bean definition profiles</h2>
<p><em>@Configuration</em> (JavaConfig) annotation has been added in Spring 3.0. <em>TestContext </em>framework (located in the <i>org.springframework.test.context</i> package) provides annotation-driven testing support. Spring 3.1 adds <b>loader</b> attribute to <i>@ContextConfiguration</i> for <i>@Configuration</i>.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<h2>c: namespace for more concise constructor injection</h2>
<p><strong>c:</strong> Namespace for XML Configuration, is a shortcut for <em>&lt;constructor-arg&gt;</em>. It allows usage of inline argument values. It is analogous to existing &#8220;p:&#8221; namespace.</p>
<h2>Support for injection against non-standard JavaBeans setters</h2>
<p>Spring 3.1 now supports injection against non-standard JavaBeans setters, useful with method-chaining, where setter methods return a reference to &#8216;this&#8217;. In earlier Spring versions, for Spring to inject against a property method, the method had to conform strictly to JavaBeans property rules, namely that the setter method must return void.</p>
<h2>Support for Servlet 3 code-based configuration of Servlet Container</h2>
<p>Spring 3.1 supports Servlet 3. It provides :</p>
<ul>
<li>Explicit support for Servlet 3.0 containers like Tomcat 7 and GlassFish 3 while preserving compatibility with Servlet 2.4+.</li>
<li>Support for XML-free web application setup (no web.xml) i.e Servlet 3.0&#8242;s ServletContainerInitializer plus Spring 3.1&#8242;s AnnotationConfigWebApplicationContext plus the environment abstraction. This means that there&#8217;s no need for web.xml to boodstrap the Spring 3.1 application.</li>
<li>Exposure of native Servlet 3.0 functionality in Spring MVC, i.e support for asynchronous request processing and standard Servlet 3.0 file upload support behind Spring&#8217;s <em>MultipartResolver </em>abstraction.</li>
</ul>
<h2>JPA EntityManagerFactory bootstrapping without persistence.xml</h2>
<p>With Spring 3.1, the JPA EntityManagerFactory can be bootstrapped without persistence.xml or other metadata files. Using the LocalContainerEntityManagerFactoryBean <em>packagesToScan </em>property, you can specify the base packages to scan for @Entity classes. This is similar to Spring&#8217;s component-scan feature for regular Spring beans.</p>
<h2>New HandlerMethod-based Support Classes For Annotated Controller Processing</h2>
<p><em>HandlerMethod </em>is a proper abstraction for the selected &#8220;handler&#8221; in Spring MVC. <b>HandlerMethod</b> support classes are:</p>
<ul>
<li>RequestMappingHandlerMapping</li>
<li>RequestMappingHandlerAdapter</li>
<li>ExceptionHandlerExceptionResolver</li>
</ul>
<h2>&#8220;consumes&#8221; and &#8220;produces&#8221; conditions in @RequestMapping</h2>
<p>Since Spring 3.1 we can specify mediatype that is accepted and provided by mapped controller method. It is much more powerful than specifying Content-Type or Accept headers as used to do before.<br />
Example:</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(method = POST, consumes =&quot;application/json&quot;, produces=&quot;application/json&quot;)
@ResponseStatus(CREATED)
@ResponseBody
</pre>
<h2>Flash Attributes and RedirectAttributes</h2>
<p>Flash attributes provide a way for one request to store attributes intended for use in another, most commonly used when using redirects like the Post/Redirect/Get pattern. Flash attributes are stored in <i>FlashMap </i> and stored in HTTP sessions, making it available to the request after the redirect and then removed immediately.</p>
<h2>URI Template Variable Enhancements</h2>
<p>URI template variables are now used in addition to request parameters when binding a request to @ModelAttribute arguments. @PathVariable method argument values are also merged into the model before rendering. A redirect string can contain placeholders for URI variables, and a @ModelAttribute method argument can be instantiated from a URI template variable as long as there is a registered Converter or PropertyEditor.</p>
<h2>@Valid On @RequestBody Controller Method Arguments</h2>
<p>Request body can be validated using Bean Validation API. An @RequestBody method argument can be annotated with @Valid to invoke automatic validation as seen in the example below:</p>
<pre class="brush: java; title: ; notranslate">
@RequestMapping(method = POST, consumes = &quot;application/json&quot;)
@ResponseStatus(CREATED)
@ResponseBody
public Task create(@Valid @RequestBody Task task) {
// No BindingResult in method signature
}
</pre>
<h2>@RequestPart Annotation On Controller Method Arguments</h2>
<p>The <em>@RequestPart</em> annotation can be used to associate a <strong>multipart/form-data</strong> request part with a method argument. It allows you to have the content of a specific multipart passed through an HttpMessageConverter, taking into consideration the multipart content-type.</p>
<h2>UriComponentsBuilder and UriComponents</h2>
<ul>
<li><b>UriComponents </b>: class is an immutable container of URI components providing access to all contained URI components.</li>
<li><b>UriComponentsBuilder</b>: class help create UriComponents instances.</li>
</ul>
<p>Together the above two classes give fine-grained control over all aspects of preparing a URI including construction, expansion from URI template variables, and encoding.</p>
<h2>Summary</h2>
<p>In this post I highlighted all the new features of Spring 3.1 though not in details. For further details you can refer the official documentation of Spring. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/new-features-spring-3-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>@Inject and @Named (JSR 330) Annotations Example</title>
		<link>http://www.javabeat.net/2013/04/inject-named-jsr-330annotations-example/</link>
		<comments>http://www.javabeat.net/2013/04/inject-named-jsr-330annotations-example/#comments</comments>
		<pubDate>Thu, 25 Apr 2013 14:06:47 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7041</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Support for JSR-330 annotations was introduced in Spring 3. These annotations are scanned the same way as the Spring annotations, only requirement would be to have the relevant jars in your classpath. You can use the following annotations in Spring 3 applications: @Inject instead of Spring’s @Autowired to inject a bean. @Named instead of Spring’s [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Support for <strong>JSR-330 annotations</strong> was introduced in Spring 3. These annotations are scanned the same way as the Spring annotations, only requirement would be to have the relevant jars in your classpath. You can use the following annotations in Spring 3 applications:</p>
<ul>
<li><b>@Inject</b> instead of Spring’s <b>@Autowired</b> to inject a bean.</li>
<li><b>@Named</b> instead of Spring’s <b>@Component</b> to declare a component/bean.(@Component can be referred from my previous post Classpath Scaning)</li>
</ul>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>@Inject and @Named Annotations Example</h2>
<p>Let&#8217;s tweak the same example I used in my previous post on <a title="spring classpath scanning and managed components" href="http://www.javabeat.net/2013/04/spring-classpath-scanning-managed-components/" target="_blank">Classpath Scanning and managed Components</a> and use the annotations <b>@Inject</b> and <b>@Named</b>. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringAnnotationExamples</i> and create a package <i>com.javabeat.injectandnamedannotations</i> under the <i>src</i> directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create source files</b>: Create Java classes Product, ProductDao, ProductDaoImpl, ProductService and MainApp under the <i>com.javabeat.injectandnamedannotations</i> package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file Beans.xml under <i>src</i> directory.</li>
</ol>
<p>Contents of <b>Product.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.injectandnamedannotations;

 public class Product {
 	String name;

 	public Product(String name) {
 		super();
 		this.name = name;
 	}

 	public String getName() {
 		return &quot;Product name is:&quot; + name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}
 }
 </pre>
<p>Contents of <b>ProductDao.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.injectandnamedannotations;

 public interface ProductDao {
 	public Product getProduct(String id);
 }
 </pre>
<p>Contents of <b>ProductDaoImpl.java</b> are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
  package com.javabeat.injectandnamedannotations;

  import java.util.HashMap;
  import java.util.Map;

  import javax.inject.Named;

  import org.springframework.context.annotation.Scope;
  import org.springframework.stereotype.Repository;

  @Named
  public class ProductDaoImpl implements ProductDao {
  	private Map&lt;String, Product&gt; products;

  	public ProductDaoImpl() {
  		products = new HashMap&lt;String, Product&gt;();
  		products.put(&quot;P1&quot;, new Product(&quot;Product1&quot;));
  		products.put(&quot;P2&quot;, new Product(&quot;Product2&quot;));
  		products.put(&quot;P3&quot;, new Product(&quot;Product3&quot;));

  	}

  	public Product getProduct(String id) {
  		return products.get(id);
  	}

  }

 </pre>
<p>Contents of <b>ProductService.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
  package com.javabeat.injectandnamedannotations;

  import javax.inject.Inject;
  import javax.inject.Named;

  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.stereotype.Service;

  @Named
  public class ProductService {
  	@Inject
  	private ProductDao productDao;

  	public Product getProductDetail(String productId) {
  		Product product = productDao.getProduct(productId);
  		return product;
  	}
  }
 </pre>
<p>Contents of <b>Beans.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
&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:aop=&quot;http://www.springframework.org/schema/aop&quot;
         xmlns:tx=&quot;http://www.springframework.org/schema/tx&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-2.5.xsd


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


http://www.springframework.org/schema/tx/spring-tx-2.5.xsd


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


http://www.springframework.org/schema/aop/spring-aop-2.5.xsd


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


http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;

         &lt;context:component-scan base-package=&quot;com.javabeat.injectandnamedannotations&quot;/&gt;

    &lt;/beans&gt;
</pre>
<p>The Contents of <b>MainApp</b> are:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat.injectandnamedannotations;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {

		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] {&quot;Beans.xml&quot; });

		ProductService productService = (ProductService) context
				.getBean(&quot;productService&quot;);
		System.out.println(productService.getProductDetail(&quot;P1&quot;).getName());
		System.out.println(productService.getProductDetail(&quot;P2&quot;).getName());
		System.out.println(productService.getProductDetail(&quot;P3&quot;).getName());

	}
}
</pre>
<p><b>Execute the code</b><br />
The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
 Product name is:Product1
 Product name is:Product2
 Product name is:Product3
 </pre>
<p>One of the limitations while using @Inject is, it has no <b>required</b> attribute.</p>
<h2>Summary</h2>
<p>In this article I demonstrated with an example the use of JSR-330 annotations- @Inject and @Named. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/inject-named-jsr-330annotations-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Spring Classpath Scanning &amp; Managed Components</title>
		<link>http://www.javabeat.net/2013/04/spring-classpath-scanning-managed-components/</link>
		<comments>http://www.javabeat.net/2013/04/spring-classpath-scanning-managed-components/#comments</comments>
		<pubDate>Tue, 23 Apr 2013 13:48:46 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7030</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In my previous articles I have explained about the some of the popular annotations in Spring @Required, @Autowired and @Qualifier. You could note from these posts that we declared all the beans or components in XML bean configuration file; this helps Spring container detect and register beans or components. In this post I shall discuss [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In my previous articles I have explained about the some of the popular annotations in Spring <a title="@Required Annotation in Spring" href="http://www.javabeat.net/2013/04/required-annotation-spring/">@Required</a>, <a title="@Autowired Annotation in Spring" href="http://www.javabeat.net/2013/04/autowired-annotation-spring/">@Autowired</a> and <a title="@Qualifier Annotation in Spring" href="http://www.javabeat.net/2013/04/qualifier-annotation-spring/">@Qualifier</a>. You could note from these posts that we declared all the beans or components in XML bean configuration file; this helps Spring container detect and register beans or components. In this post I shall discuss about another feature of Spring i.e.<b>Component Scanning</b>. This means Spring is able to auto scan, detect and instantiate beans from pre-defined project package, hence saving us from tedious beans/component declaration in XML file.</p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>Stereotype Annotations</h2>
<p>The basic annotation denoting a Spring-managed component is <b>@Component</b> (Denotes a auto scan component.). Other more particular stereotypes include</p>
<ul>
<li>@Repository: Denotes DAO component in the persistence layer.</li>
<li>@Service: Denotes a Service component in the business layer.</li>
<li>@Controller: Denotes a controller component in the presentation layer.</li>
</ul>
<p>If you look at the source code for each of these components (<i>org.springframework.stereotype.Repository</i>, <i>org.springframework.stereotype.Service</i>, <i>org.springframework.stereotype.Controller</i>), they internally use the <b>@Component</b> annotation. Though you can use only @Component annotation throughout your code, this would not be considered as a good practise. Hence using @Repository, @Service, @Controller annotations helps us seperate the persistence, business and presentation layers.</p>
<h2>Example for Auto Scan Components<b><br />
</b></h2>
<p>The following example demonstrates the use of all the above annotations mentioned. Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringClassPathScanningExample</i> and create a package <i>com.javabeat</i> under the <i>src</i> directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create source files</b>: Create Java classes <i>Product</i>, interface <i>ProductDao</i>, implementation <i>ProductDaoImpl</i>, <i>ProductService</i> and <i>MainApp</i> under the com.javabeat package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file bean.xml under <i>src</i> directory.</li>
</ol>
<p>Contents of <b>Product.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat;

 public class Product {
 	String name;

 	public Product(String name) {
 		super();
 		this.name = name;
 	}

 	public String getName() {
 		return &quot;Product name is:&quot; + name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}
 }
 </pre>
<p>This class contains only name field and its respective getter and setter methods.</p>
<p><em>ProductDao </em> is an interface for the Data Access Object (DAO), which is responsible for accessing data from the database. This has a single method <i>getProduct()</i>, which Product object from the table by its ID. Contents of <b>ProductDao.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat;

 public interface ProductDao {
 	public Product getProduct(String id);
 }
 </pre>
<p>In a production application, we need to implement this DAO interface using a data-access technology such as JDBC or object/relational mapping. But for testing purposes, let’s use maps to store the Product instances as shown below. Contents of <b>ProductDaoImpl.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
  package com.javabeat;

  import java.util.HashMap;
  import java.util.Map;

  import org.springframework.stereotype.Component;

  @Component
  public class ProductDaoImpl implements ProductDao {
  	private Map&lt;String, Product&gt; products;

  	public ProductDaoImpl() {
  		products = new HashMap&lt;String, Product&gt;();
  		products.put(&quot;P1&quot;, new Product(&quot;Product1&quot;));
  		products.put(&quot;P2&quot;, new Product(&quot;Product2&quot;));
  		products.put(&quot;P3&quot;, new Product(&quot;Product3&quot;));

  	}

  	public Product getProduct(String id) {
  		return products.get(id);
  	}

  }
 </pre>
<p>The component scanning feature as explained above, can automatically scan, detect, and instantiate your components from the classpath. By default, Spring can detect all components with a stereotype annotation. We can apply basic annotation <b>@Component to ProductDaoImpl class as shown above.</b></p>
<p>We also need a service object, acting as a facade, to provide the sequence generation service. Internally, this service object will interact with the DAO to handle the Product generation requests. So it requires a reference to the DAO as in the service class below. Contents of <b>ProductService.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;

 @Component
 public class ProductService {
 	@Autowired
 	private ProductDao productDao;

 	public Product getProductDetail(String productId) {
 		Product product = productDao.getProduct(productId);
 		return product;
 	}
 }
 </pre>
<p>We will also apply <b>@Component</b> stereotype annotation to the ProductService class for Spring to detect it. In addition, we have applied the <b>@Autowired</b> annotation to the DAO field for Spring to auto-wire it by type. Note that because we’re using the annotation on a field, you don’t need a setter method here.</p>
<p><span style="color: #000080;"><strong>Now that we have applied the stereotype annotations to our component classes, we ask Spring to scan them by declaring a single XML element: . In this element, you need to specify the <i>package</i> for scanning your components (<i>You can use commas to separate multiple packages for scanning.</i>)</strong></span>. Then the specified package and all its sub packages will be scanned. Spring will give the bean a name created by <i>lower casing</i> the first character of the class and using the rest of the camel-cased name for the bean name. In our case the base package name is <i>com.javabeat</i>. Contents of <b>bean.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 &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:aop=&quot;http://www.springframework.org/schema/aop&quot;
          xmlns:tx=&quot;http://www.springframework.org/schema/tx&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-2.5.xsd


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


http://www.springframework.org/schema/tx/spring-tx-2.5.xsd


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


http://www.springframework.org/schema/aop/spring-aop-2.5.xsd


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


http://www.springframework.org/schema/context/spring-context-2.5.xsd&quot;&gt;

          &lt;context:component-scan base-package=&quot;com.javabeat&quot;/&gt;

     &lt;/beans&gt;
 </pre>
<p>Contents of <b>MainApp</b> are as below:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat;

 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class MainApp {
 	public static void main(String[] args) {

 		ApplicationContext context = new ClassPathXmlApplicationContext(
 				new String[] { &quot;bean.xml&quot; });

 		ProductService productService = (ProductService) context.getBean(&quot;productService&quot;);
 		System.out.println(productService.getProductDetail(&quot;P1&quot;).getName());
 		System.out.println(productService.getProductDetail(&quot;P2&quot;).getName());
 		System.out.println(productService.getProductDetail(&quot;P3&quot;).getName());

 	}
 }
 </pre>
<p>Here you can note the statement:</p>
<pre class="brush: java; title: ; notranslate">
 ProductService productService = (ProductService) context.getBean(&quot;productService&quot;);
 </pre>
<p>This element will also register an <b>AutowiredAnnotationBeanPostProcessor</b> instance that can auto-wire properties with the <b>@Autowired</b> annotation.</p>
<p><b>Execute the code</b></p>
<p>The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
Product name is:Product1
Product name is:Product2
Product name is:Product3
 </pre>
<p>As mentioned in section <i>Stereotype Annotations</i>, @Component is a basic stereotype for denoting components of general purposes. The other types <em>@Repository</em> and <em>@Service</em> annotations can be used for our above example as shown below, without affecting its functionality and result. <b>@Repository</b> stereotype denotes a DAO component in the persistence layer, hence we will apply it to our ProductDaoImpl as shown below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

@Repository
public class ProductDaoImpl implements ProductDao {
	private Map&lt;String, Product&gt; products;

	public ProductDaoImpl() {
		products = new HashMap&lt;String, Product&gt;();
		products.put(&quot;P1&quot;, new Product(&quot;Product1&quot;));
		products.put(&quot;P2&quot;, new Product(&quot;Product2&quot;));
		products.put(&quot;P3&quot;, new Product(&quot;Product3&quot;));

	}

	public Product getProduct(String id) {
		return products.get(id);
	}

}
</pre>
<p><b>@Service</b> stereotype denotes a service component in the service layer. Hence it can be applied as below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {
	@Autowired
	private ProductDao productDao;

	public Product getProductDetail(String productId) {
		Product product = productDao.getProduct(productId);
		return product;
	}
}
</pre>
<h2>Filtering Components to Scan</h2>
<p>By default, Spring will detect all classes annotated with @Component, @Repository, @Service, @Controller,or your custom annotation type that is itself annotated with @Component. You can customize the scan by applying one or more include/exclude filters.</p>
<p>Spring supports five types of filter expressions.</p>
<ol>
<li><i>annotation</i>: You can specify an annotation type for filtering.</li>
<li><i>assignable</i>: You can specify a class/interface for filtering.</li>
<li><i>aspectj</i>: Allow you to specify an AspectJ pointcut expression for matching the classes.</li>
<li><i>regex</i>: Allows you to specify a regular expression for matching the classes.</li>
<li><i>custom</i>: A custom implementation of the org.springframework.core.type .TypeFilter interface.</li>
</ol>
<p>You can disable the default filters with the <i>use-default-filters</i> attribute.<br />
For example, the following component scan includes all classes whose name contains the word Dao or Service, and excludes the classes with the @Controller annotation:</p>
<pre class="brush: java; title: ; notranslate">
&lt;beans ...&gt;
&lt;context:component-scan base-package=&quot;com.javabeat&quot;&gt;
&lt;context:include-filter type=&quot;regex&quot; expression=&quot;com\.javabeat\..*Dao.*&quot; /&gt;
&lt;context:include-filter type=&quot;regex&quot; expression=&quot;com\.javabeat\..*Service.*&quot; /&gt;
&lt;context:exclude-filter type=&quot;annotation&quot; expression=&quot;org.springframework.stereotype.Controller&quot; /&gt;
&lt;/context:component-scan&gt;
&lt;/beans&gt;
</pre>
<p>Because you have applied include filters to detect all classes whose name contains the word Dao or Service, the ProductDaoImpl and ProductService components can be auto-detected even without a stereotype annotation.</p>
<h2>Naming Detected Components</h2>
<p>By default, Spring will name the detected components by lowercasing the first character of the nonqualified class name. For example, the ProductService class will be named as productService. You can define the name for a component explicitly by specifying it in the stereotype annotation’s value as shown below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;
.......
import org.springframework.stereotype.Service;

@Service(&quot;productService&quot;)
public class ProductService {
	@Autowired
	private ProductDao productDao;
.........
.........
}
}

}
</pre>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

..........
import org.springframework.stereotype.Repository;

@Repository(&quot;productDao&quot;)
public class ProductDaoImpl implements ProductDao {
	........
	........

}

</pre>
<p>We can develop our own naming strategy by implementing the <i>BeanNameGenerator</i> interface and specifying it in the <i>name-generator</i> attribute of the <b></b> element.</p>
<ul>
<li><a href="http://www.javabeat.net/2007/07/introduction-to-springs-aspect-oriented-programmingaop/">Spring Aspect Oriented Programming (AOP)</a></li>
</ul>
<h2>Providing Scope for Auto detected Components</h2>
<p>By default most common scope for auto detected components is singleton. However, sometimes you need other scopes, which Spring 2.5 provides with a new @Scope annotation. We simply need to provide the name of the scope within the annotation as shown below:</p>
<pre class="brush: java; title: ; notranslate">
package com.javabeat;

.......
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

@Scope(&quot;prototype&quot;)
@Repository(&quot;productDao&quot;)
public class ProductDaoImpl implements ProductDao {
	private Map&lt;String, Product&gt; products;
......
.....
	}
}
</pre>
<h2>Summary</h2>
<p>In this post we saw how Spring auto detects the components from classpath, hence relieving us of the hassles of XML configurations.<br />
By default, it can detect all components with particular stereotype annotations. But you can further include or exclude your components with filters. You can also provide scopes for the auto detected components. Component scanning is a powerful feature that can reduce the amount of configurations. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. <strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/spring-classpath-scanning-managed-components/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>@Resource, @PostConstruct and @PreDestroy Annotations Example</title>
		<link>http://www.javabeat.net/2013/04/resource-postconstruct-predestroy-annotations-example/</link>
		<comments>http://www.javabeat.net/2013/04/resource-postconstruct-predestroy-annotations-example/#comments</comments>
		<pubDate>Sun, 21 Apr 2013 11:30:22 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7020</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this post I shall cover the JSR250 annotations. Introduced in Spring 2.5, it added support for JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations. In my previous articles I have explained about the some of the popular annotations in Spring @Required, @Autowired and @Qualifier. Also please read about How to write Custom Spring Callback Methods? also read: follow [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this post I shall cover the JSR250 annotations. Introduced in Spring 2.5, it added support for JSR-250 based annotations which include <b>@Resource</b>, <b>@PostConstruct</b> and <b>@PreDestroy</b> annotations. In my previous articles I have explained about the some of the popular annotations in Spring <a title="@Required Annotation in Spring" href="http://www.javabeat.net/2013/04/required-annotation-spring/">@Required</a>, <a title="@Autowired Annotation in Spring" href="http://www.javabeat.net/2013/04/autowired-annotation-spring/">@Autowired</a> and <a title="@Qualifier Annotation in Spring" href="http://www.javabeat.net/2013/04/qualifier-annotation-spring/">@Qualifier</a>. Also please read about <a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>@Resource vs @Autowired</h2>
<p><strong>@Resource</strong> is similar to <a href="http://www.javabeat.net/2013/04/autowired-annotation-spring/">@Autowired</a> in functionality. @Autowired is Spring&#8217;s Annotation(only usable in Spring) whereas @Resource is JSR-250 Common Annotation equivalent (works the same in Java EE 5). Though the functionality for the two annotations being same, @Autowired is the only annotation that you can put on constructors.</p>
<p>By default auto wiring is done by <b>object type</b>. If you have two beans of the same type, then there is ambiguity that Spring can&#8217;t figure out which of the two beans to inject. That is when <strong>@Qualifier</strong> is used. It helps fix the ambiguity and tell Spring which of the two beans to inject. Use @Qualifier with @Autowired. <span style="color: #000080;"><strong>With @Resource you can just put the bean name in the annotation as an attribute.</strong></span></p>
<h2>@PostConstruct and @PreDestroy</h2>
<p>These annotations are alternative methods for defining initialization and destruction callback functions which I covered in post <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</p>
<h2>Example using @Resource, @PostConstruct and @PreDestroy</h2>
<p>The example in post, demostrates the use of @Resource, @PostConstruct and @PreDestroy annotations.</p>
<p>Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringAnnotationExamples</i> and create a package <i>com.javabeat.jsrannotations</i> under the src directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create source files</b>: Create Java classes Product,Type and MainApp under the com.javabeat.jsrannotations package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file BeansJSRAnnotation.xml under <i>src</i> directory.</li>
</ol>
<p>The class Product.java, is simple POJO class having name,price and an object of Type class. Contents of <b>Product.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.jsrannotations;

 import javax.annotation.PostConstruct;
 import javax.annotation.PreDestroy;
 import javax.annotation.Resource;

 public class Product {
 	private Integer price;
 	private String name;

 	@Resource(name = &quot;typeB&quot;)
 	private Type type;

 	public Integer getPrice() {
 		return price;
 	}

 	public void setPrice(Integer price) {
 		this.price = price;
 	}

 	public Type getType() {
 		return type;
 	}

 	public String getName() {
 		return name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}

 	@PostConstruct
 	public void init() {
 		System.out.println(&quot;In init block of Product&quot;);
 	}

 	@PreDestroy
 	public void destroy() {
 		System.out.println(&quot;In destroy block of Product&quot;);
 	}
}
 </pre>
<p>Here you note that we have used @Resource annotation. @PostConstruct and @PreDestroy are used for their respective lifecycle callback methods. Here you can see, I&#8217;ve used the @Qualifier annotation alongwith the @Autowired annotation.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>The Type.java class is also a POJO class having a string object called &#8220;type&#8221;. Contents of <b>Type.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.jsrannotations;

 public class Type {

  	private String productType;

 	public String getProductType() {
 		return productType;
 	}

 	public void setProductType(String productType) {
 		this.productType = productType;
 	}

 }
 </pre>
<p>Contents of <b>MainApp</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.jsrannotations;

 import org.springframework.context.support.AbstractApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class MainApp {
 	public static void main(String[] args) {
 		AbstractApplicationContext context = new ClassPathXmlApplicationContext(
 				&quot;BeansJSRAnnotation.xml&quot;);

 		Product product = (Product) context.getBean(&quot;product&quot;);

 		System.out.println(&quot;Product Name : &quot; + product.getName());
 		System.out.println(&quot;Price : &quot; + product.getPrice());

 		Type productType = product.getType();

 		System.out.println(product.getName() + &quot; is of type:&quot;
 				+ productType.getProductType());
 		context.registerShutdownHook();
 	}
}
</pre>
<p>Here you need to register a shutdown hook registerShutdownHook() method that is declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.</p>
<p>Contents of <b>BeansJSRAnnotation.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
&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:annotation-config /&gt;

	&lt;!-- Definition for Product bean --&gt;
	&lt;bean id=&quot;product&quot; class=&quot;com.javabeat.jsrannotations.Product&quot; init-method=&quot;init&quot; destroy-method=&quot;destroy&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;ProductA&quot; /&gt;
		&lt;property name=&quot;price&quot; value=&quot;400&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;typeA&quot; class=&quot;com.javabeat.jsrannotations.Type&quot;&gt;
		 &lt;property name=&quot;productType&quot; value=&quot;Export&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;typeB&quot; class=&quot;com.javabeat.jsrannotations.Type&quot;&gt;
		 &lt;property name=&quot;productType&quot; value=&quot;Import&quot; /&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</pre>
<p>As you can note here we are having two beans of same type.In Product.java I&#8217;ve used @Resource(&#8220;typeB&#8221;) it means we want to autowire Type property of Product with bean id=&#8221;typeB&#8221; in XML configuration file. You can also note that <i> init-method</i> and <i>destroy-method</i> attribute are used to specify the name of the method that has a return void, no argument method signature (init() and destroy method respectively from Product.java).</p>
<ul>
<li><a href="http://www.javabeat.net/2007/07/introduction-to-springs-aspect-oriented-programmingaop/">Spring Aspect Oriented Programming (AOP)</a></li>
</ul>
<p><b>Execute the code</b></p>
<p>The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
In init block of Product
Product Name : ProductA
Price : 400
ProductA is of type:Import
In destroy block of Product
</pre>
<h2>Summary</h2>
<ul>
<li><a title="@Qualifier Annotation in Spring" href="http://www.javabeat.net/2013/04/qualifier-annotation-spring/">@Qualifier Annotation in Spring</a></li>
<li><a title="@Autowired Annotation in Spring" href="http://www.javabeat.net/2013/04/autowired-annotation-spring/">@Autowired Annotation in Spring</a></li>
<li><a title="@Required Annotation in Spring" href="http://www.javabeat.net/2013/04/required-annotation-spring/">@Required Annotation in Spring</a></li>
</ul>
<p>In this post I discussed with and example about the use of JSR250 annotations. In the next article I shall cover the JSR330 annotations(@Inject and @Named). If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/resource-postconstruct-predestroy-annotations-example/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>@Qualifier Annotation in Spring</title>
		<link>http://www.javabeat.net/2013/04/qualifier-annotation-spring/</link>
		<comments>http://www.javabeat.net/2013/04/qualifier-annotation-spring/#comments</comments>
		<pubDate>Sat, 20 Apr 2013 12:33:26 +0000</pubDate>
		<dc:creator>Manisha Patil</dc:creator>
				<category><![CDATA[Spring Framework]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=7016</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>In this post I shall cover another annotation @Qualifier which helps fine-tune annotation-based autowiring. In the previous post we saw how we could use @Autowired annotation on setter methods, fields and constructors. There may be scenarios when we create more than one bean of the same type and want to wire only one of them [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>In this post I shall cover another annotation <strong>@Qualifier</strong> which helps fine-tune annotation-based autowiring. In the previous post we saw how we could use <a href="http://www.javabeat.net/2013/04/autowired-annotation-spring/"><strong>@Autowired</strong></a> annotation on setter methods, fields and constructors. There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using @Qualifier annotation along with the <strong>@Autowired</strong> annotation.</p>
<p><strong>also read</strong>: follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a></p>
<ul>
<li><a href="http://www.javabeat.net/2013/03/spring-tutorials/">Spring Tutorials ( Collection for Spring reference tutorials)</a></li>
<li><a href="http://www.javabeat.net/2009/02/spring-framework-interview-questions/">Spring Framework Interview Questions</a></li>
<li><a href="http://www.javabeat.net/2011/05/introduction-to-spring-ldap/">Introduction to Spring LDAP</a></li>
<li><a title="How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/">How to write Custom Spring Callback Methods?</a></li>
</ul>
<h2>@Qualifier Example</h2>
<p>Let us have working Eclipse IDE in place and follow the following steps to create a Spring application:</p>
<ol>
<li><b>Create a project</b>: Create a project with a name <i>SpringAnnotationExamples</i> and create a package <i>com.javabeat.qualifierexample</i> under the src directory in the created project.</li>
<li><b>Add Libraries</b>: Add required Spring libraries using Add External JARs option as explained in the article <a title=" How to write Custom Spring Callback Methods?" href="http://www.javabeat.net/2013/04/custom-spring-callback-methods/" target="_blank">Customizing callback methods</a>.</li>
<li><b>Create source files</b>: Create Java classes Product,Type and MainApp under the com.javabeat.qualifierexample package.</li>
<li><b>Create configuration file</b>: Create XML based configuration file BeansQualifierAnnotation.xml under <i>src</i> directory.</li>
</ol>
<p>The class Product.java, is simple POJO class having name,price and an object of Type class. Contents of <b>Product.java</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.qualifierexample;

 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;

 public class Product {
 	private Integer price;
 	private String name;

 	@Autowired
 	@Qualifier(&quot;typeB&quot;)
 	private Type type;

 	public Integer getPrice() {
 		return price;
 	}

 	public void setPrice(Integer price) {
 		this.price = price;
 	}

 	public Type getType() {
 		return type;
 	}

 	public String getName() {
 		return name;
 	}

 	public void setName(String name) {
 		this.name = name;
 	}
 }
 </pre>
<p>Here you can see, I&#8217;ve used the @Qualifier annotation alongwith the @Autowired annotation.</p>
<p>The Type.java class is also a POJO class having a string object called &#8220;type&#8221;. Contents of <b>Type.java</b> are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.autowireexample;

 public class Type {

 	private String type;

 	public String getType() {
 		return type;
 	}

 	public void setType(String type) {
 		this.type = type;
 	}
 }
 </pre>
<p>Contents of <b>MainApp</b> are:</p>
<pre class="brush: java; title: ; notranslate">
 package com.javabeat.qualifierexample;

 import org.springframework.context.ApplicationContext;
 import org.springframework.context.support.ClassPathXmlApplicationContext;

 public class MainApp {
 	public static void main(String[] args) {
 	      ApplicationContext context =
 	             new ClassPathXmlApplicationContext(&quot;BeansQualifierAnnotation.xml&quot;);

 	      Product product = (Product) context.getBean(&quot;product&quot;);

 	      System.out.println(&quot;Product Name : &quot; + product.getName() );
 	      System.out.println(&quot;Price : &quot; + product.getPrice() );

 	      Type productType = product.getType();

 	      System.out.println(product.getName()+&quot; is of type:&quot; + productType.getType() );
 	   }
 }
</pre>
<p>Contents of <b>BeansQualifierAnnotation.xml</b> are:</p>
<pre class="brush: java; title: ; notranslate">
&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:annotation-config /&gt;

	&lt;!-- Definition for Product bean --&gt;
	&lt;bean id=&quot;product&quot; class=&quot;com.javabeat.qualifierexample.Product&quot;&gt;
		&lt;property name=&quot;name&quot; value=&quot;ProductA&quot; /&gt;
		&lt;property name=&quot;price&quot; value=&quot;400&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;typeA&quot; class=&quot;com.javabeat.qualifierexample.Type&quot;&gt;
		 &lt;property name=&quot;type&quot; value=&quot;Export&quot; /&gt;
	&lt;/bean&gt;
	&lt;bean id=&quot;typeB&quot; class=&quot;com.javabeat.qualifierexample.Type&quot;&gt;
		 &lt;property name=&quot;type&quot; value=&quot;Import&quot; /&gt;
	&lt;/bean&gt;

&lt;/beans&gt;
</pre>
<p>As you can note here we are having two beans of same type. In Product.java I&#8217;ve used @Qualifier(&#8220;typeB&#8221;) it means we want to autowire Type property of Product with bean id=&#8221;typeB&#8221; in XML configuration file.</p>
<ul>
<li><a href="http://www.javabeat.net/2007/07/introduction-to-springs-aspect-oriented-programmingaop/">Spring Aspect Oriented Programming (AOP)</a></li>
</ul>
<p><b>Execute the code</b><br />
The final step is run the application. Once all the above code is ready execute and the below output appears on the console:</p>
<pre class="brush: java; title: ; notranslate">
Product Name : ProductA
Price : 400
ProductA is of type:Import
</pre>
<h2>Summary</h2>
<ul>
<li><a title="@Autowired Annotation in Spring" href="http://www.javabeat.net/2013/04/autowired-annotation-spring/">@Autowired Annotation in Spring</a></li>
<li><a title="@Required Annotation in Spring" href="http://www.javabeat.net/2013/04/required-annotation-spring/">@Required Annotation in Spring</a></li>
</ul>
<p>In this post we saw how to configure the Spring container using the <strong>@Qualifier</strong> annotation. This annotation can be used for on setter methods, on fields, on constructors, with arguments. Examples for the same has been demonstrated. In the next article I shall discuss about JSR-250 Annotations. If you are interested in receiving the future articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>. follow us on <a href="http://www.twitter.com/javabeat" target="_blank">@twitter</a> and <a href="https://www.facebook.com/javabeat.net" target="_blank">@facebook</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/04/qualifier-annotation-spring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
