<?xml version="1.0" encoding="utf-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">
<title>Seema Richard&apos;s Blog</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/seemarich/" />
<modified>2007-11-27T12:15:02Z</modified>
<tagline></tagline>
<id>tag:weblogs.java.net,2008:/blog/seemarich/436</id>
<generator url="http://www.movabletype.org/" version="3.01D">Movable Type</generator>
<copyright>Copyright (c) 2007, seemarich</copyright>
<entry>
<title>Annotation based configuration in Spring</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/seemarich/archive/2007/11/annotation_base_1.html" />
<modified>2007-11-27T12:15:02Z</modified>
<issued>2007-11-27T12:14:46Z</issued>
<id>tag:weblogs.java.net,2007:/blog/seemarich/436.8703</id>
<created>2007-11-27T12:14:46Z</created>
<summary type="text/plain">The latest annotation-based configuration approach in Spring has made application development simpler and easier.</summary>
<author>
<name>seemarich</name>

<email>seemamani@asianetindia.com</email>
</author>
<dc:subject>Open Source</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/seemarich/">
<![CDATA[<html>

<head>

<style type="text/css" id="internalStyle">
  body {
    font-family: arial, helvetica, sans-serif;
    font-size: 10pt;
  }

  pre.listing {
    display: table;
    color: black;
    background-color: lightgray;
    border-style: solid;
    border-width: 1px;
    border-color: darkgray;
    margin: 8px 0px 5px 0px;
    padding: 2px;
    width: auto; 
    overflow: auto;  
    font-family: monospace;
  }

  .warning {
    color: red;
    font-size:  0.8em;
    text-align: center;
  }

  .mh1 {
    color: #202080;
    font-size:  1.2em;
    font-weight: bold;
  }

  .mh2 {
    color: #202080;

    font-size:  1em;
    font-weight: bold;
  }

  .mh3 {
    font-size:  1em;
    text-decoration: underline;  
  }

  .system {
    font-family: monospace;
  }

  .file {
    font-family: monospace;
  }

  .jdkfile {
    font-family: monospace;
  }

  .code {
    font-family: monospace;
  }

  a {
    text-decoration: none;
  }
</style>


<title> Exploring annotations in Spring 2.5 </title>

</head>

<body>

<p>
It is now possible to configure Spring's dependency injection with annotations. This means that 

annotations can be used in Spring to mark fields, methods and classes that need dependency 

injection. Spring also supports auto-wiring of the bean dependencies, that is, resolving the 

collaborating beans by inspecting the contents of the BeanFactory. Now there are annotations that 

can be used to indicate fields that are to be auto-wired. Furthermore, auto-detection of 

annotated components in the classpath is also supported now. When these capabilities are 

combined, the amount of configuration and dependency mapping in the Spring configuration files is 

reduced drastically.
</p>

<p>
According to the Spring development team, the core theme of Spring 2.5 that was released in 

October 2007 is to provide comprehensive support for configuration annotations in application 

components. Annotation support was first announced in Spring 2.0, and has been significantly 

enhanced in Spring 2.5. It introduces support for a complete set of configuration annotations.
</P>

<P>
I'll briefly discuss the annotation-driven configuration and auto-detection support in Spring 2.5 

with the help of a simple tutorial.
</p>

<p>
<b>
What you need before you start
</b>
</p>

<p>
You need the following software to try out the tutorial.
</P>

<p>
<b>
<a href="http://java.sun.com/javase/downloads/index_jdk5.jsp">Java 5.0</a>
<br>
<a href="http://www.springframework.org/download">Spring Framework 2.5</a>
</b>
</P>

<P>

You also need the following jars in your classpath. These are available with the Spring 

distribution.

<ul>
<li>spring.jar</li>
<li>asm-2.2.3.jar</li>
<li>asm-commons-2.2.3.jar</li>
<li>aspectjweaver.jar</li>
<li>aspectjrt.jar</li>
<li>hsqldb.jar</li>
<li>commons-logging.jar</li>
<li>log4j-1.2.14.jar</li>
<li>junit-4.4.jar</li>
<li>spring-test.jar</li>
<li>common-annotations.jar(This is not required if Java 6.0 or later is used)</li>
</ul>

</p>

<p>
<b>
Adding the classes and interfaces for the example
</b>
</p>

<P>
The example is just a simple service that returns a different message when an employee is hired 

or fired. 
</p>

<p>
Let me start with the EmployeeService interface. 
</p>


<div class="listing cpp"><pre class="listing">
package emptest;

public interface EmployeeService {
	String hire(String name);

	String fire(String name);
}

</pre></div>


<p>
Here is a simple class that implements this interface.
</p>

<div class="listing cpp"><pre class="listing">
@Service
public class EmployeeServiceImpl implements EmployeeService {
	@Autowired
	private EmployeeDao employeeDao;

	public String hire(String name) {
		String message = employeeDao.getMessage("Hire");
		return name + ", " + message;
	}

	public String fire(String name) {
		String message = employeeDao.getMessage("Fire");
		return name + ", " + message;
	}

	public void setEmployeeDao(EmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}
}
</pre></div>

<p>
<b>Stereotype Annotations</b>
</p>

<p>
Classes marked with stereotype annotations are candidates for auto-detection by Spring when using 

annotation-based configuration and classpath scanning. The @Component annotation is the main 

stereotype that indicates that an annotated class is a "component". 
</p>

<p>
The @Service stereotype annotation used to decorate the EmployeeServiceImpl class is a 

specialized form of the @Component annotation. It is appropriate to annotate the service-layer 

classes with @Service to facilitate processing by tools or anticipating any future 

service-specific capabilities that may be added to this annotation. 
</p>

<p>
The @Repository annotation is yet another stereotype that was introduced in Spring 2.0 itself. 

This annotation is used to indicate that a class functions as a repository (the EmployeeDAOImpl below demonstrates the use) and needs to have exception translation applied transparently on it. The benefit of exception translation is that the service layer only has to deal with exceptions from Spring's DataAccessException hierarchy, even when using plain JPA in the DAO classes. 
</p>

<p>
<b>@autowired</b>
</p>

<p>
Another annotation used in EmployeeServiceImpl is @autowired . This is used to autowire the 

dependency of the EmployeeServiceImpl on the EmployeeDao . Here is the EmployeeDao interface.
</p>

<p>
<div class="listing cpp"><pre class="listing">
public interface EmployeeDao {
    String getMessage(String messageKey);
}
</pre></div>
</p>


<p>
The implementing class EmployeeDaoImpl uses the @Repository annotation.
</p>

<p>
<div class="listing cpp"><pre class="listing">
@Repository
public class EmployeeDaoImpl implements EmployeeDao {

	private SimpleJdbcTemplate jdbcTemplate;

	public String getMessage(String messageKey) {
		return jdbcTemplate.queryForObject(
				"select message from messages where messagekey = ?",
				String.class, messageKey);
	}

	@Autowired
	public void createTemplate(DataSource dataSource) {
		this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	}
}

</pre></div>
</p>


<p>
Here again, the DataSource implementation is autowired to the argument taken by the method that 

creates the SimpleJdbcTemplate object.
</p>

<p>
<b>Simplified Configuration</b>
</p>

<p>
The components discovered by classpath scanning are turned into Spring bean definitions, not 

requiring explicit configuration for each such bean. So the Spring configuration xml file is very 

simple.
</p>

<div class="listing cpp"><pre class="listing">
&lt;beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-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">
	&lt;context:annotation-config />
	&lt;context:component-scan base-package="emptest" />
	&lt;aop:aspectj-autoproxy />

	&lt;context:property-placeholder location="classpath:jdbc.properties" />

	&lt;bean id="dmdataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		&lt;property name="driverClassName" value="${jdbc.driver}" />
		&lt;property name="url" value="${jdbc.url}" />
		&lt;property name="username" value="${jdbc.username}" />
		&lt;property name="password" value="${jdbc.password}" />
	&lt;/bean>
  
&lt;/beans>

</pre></div>

<p>
Now let me explain the new configurations in the above Spring context file. The 

&lt;context:annotation-config /> element is used to automatically register all of Spring's 

standard post-processors for annotation-based configuration. The &lt;context:component-scan 

annotation> element is used to enable autodetection of the stereotyped classes in the package 

emptest . Since the AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor 

are both included implicitly when using the component-scan element, the 

&lt;context:annotation-config/> element can be omitted.
</p>

<p>
The properties for the data source are taken from the jdbc.properties file in the classpath. The 

property placeholders are configured with the &lt;context:property-placeholder> element.
</p>

<p>
The &lt;aop:aspectj-autoproxy/> element is used to enable @AspectJ support in Spring. 
</p>

<p>
<b>
@Aspect
</b>
</p>

<p>
The @Aspect annotation on a class marks it as an aspect along with @Pointcut definitions and 

advice (@Before, @After, @Around) as demonstrated in the TraceLogger class defintion below. The 

PointCut is applied for all methods in the EmployeeServiceImpl class. The @Before annotation 

indicates that the log() method in the TraceLogger is to be invoked by Spring AOP prior to 

calling any method in EmployeeServiceImpl.
</p>

<div class="listing cpp"><pre class="listing">
@Component
@Aspect
public class TraceLogger {
	private static final Logger LOG = Logger.getLogger(TraceLogger.class);

	@Pointcut("execution(* emptest.EmployeeServiceImpl.*(..))")
	public void empTrace() {
	}

	@Before("empTrace()")
	public void log(JoinPoint joinPoint) {
		LOG.info("Before calling " + joinPoint.getSignature().getName()
				+ " with argument " + joinPoint.getArgs()[0]);
	}

}
</pre></div>

<p>
Since there is no definition provided for TraceLogger in the Spring context file, it is marked 

for auto-detection from the classpath using the @Component annotation.
</p>

<p>
<b>
@Qualifier and @Resource
</b>
</p>

<p>
Suppose there is one more DataSource configuration in the spring context file as follows.
</b>

<div class="listing cpp"><pre class="listing">
&lt;bean id="jndidataSource"
	class="org.springframework.jndi.JndiObjectFactoryBean">
		&lt;property name="jndiName" value="jdbc/test" />
&lt;/bean>
</pre></div>

<p>
Since auto-detection is enabled, auto-wiring will fail since both data source beans are equally 

eligible candidates for wiring. It is possible to achieve by-name auto-wiring by providing a bean 

name within the @Qualifier annotation as follows. The below method injects the DataSource 

implementation by specifying the name “dmdataSource”. 
</p>

<div class="listing cpp"><pre class="listing">
@Autowired
public void createTemplate(@Qualifier("dmdataSource") DataSource dataSource) {
 	this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
</pre></div>

<p>
<b>
JSR-250 Annotations
</b>
</p>

<p>
Spring also provides support for Java EE 5 Common Annotations (JSR-250). The supported 

annotations are @Resource, @PostConstruct and @PreDestroy. The @Resource annotation is also 

supported by Spring for autowiring as shown in the below code, the bean name to be autowired is 

passed.
</p>

<div class="listing cpp"><pre class="listing">
@Resource(name = "dmdataSource")
public void createTemplate(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
</pre></div>

<p>
The JSR-250 lifecycle annotations @PostConstruct and @PreDestroy can be used to specify 

initialization callbacks and destruction callbacks respectively. To demonstrate the use of these, 

I’m adding the following code to the EmployeeDaoImpl class.
</p>

<div class="listing cpp"><pre class="listing">
@PostConstruct
public void initialize() {
	jdbcTemplate.update("create table messages (messagekey varchar(20), message 

varchar(100))");
	jdbcTemplate.update("insert into messages (messagekey, message) values ('Hire', Congrats! 

You are hired')");
	jdbcTemplate.update("insert into messages (messagekey, message) values ('Fire', 'Sorry! 

You are fired')");
}

@PreDestroy
public void remove() {
	jdbcTemplate.update("drop table messages");
}

</pre></div>

<p>
<b>
Unit Testing
</b>
</p>

<p>
Before testing the service implementation, I provided the database configuration details in the 

jdbc.properties file as follows.
</p>

<pre class="listing">
jdbc.driver=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:blog
jdbc.username=sa
jdbc.password=
</pre>

<p>
Here is the class I wrote for unit testing. 
</p>

<div class="listing cpp"><pre class="listing">
public class EmployeeServiceImplTests extends
		AbstractDependencyInjectionSpringContextTests {
	@Autowired
	private EmployeeService employeeService;

	@Override
	protected String[] getConfigLocations() {
		return new String[] { "context.xml" };
	}

	public void testHire() {
		String name = "Tom";
		String message = employeeService.hire(name);
		assertEquals(name + ", " + "Congrats! You are hired", message);
	}

	public void testGermanWelcome() {
		String name = "Jim";
		String message = employeeService.fire(name);
		assertEquals(name + ", " + "Sorry! You are fired", message);
	}

	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
}
</pre></div>

<p>
<b>
Resources
</b>
</p>

<p>
You can download the source code for this tutorial <a 

href="http://weblogs.java.net/blog/seemarich/archive/springannotations/SpringAnnotationsTestApp.z

ip">here.</a>
</p>

<p>
The inputs from the following sources were very helpful in writing this tutorial.
</p>

<p>
<a href="http://www.theserverside.com/tt/articles/article.tss?l=IntrotoSpring25">Rod Johnson's 

article on Spring 2.5</a>
<br>
<a href="http://static.springframework.org/spring/docs/2.5.x/reference/index.html">Spring 2.5 

Documentation</a>
</p>

<p>
<b>
Summary
</b>
</p>

<p>
I hope this discussion has opened up the possibilities offered by the annotation-based 

configuration capabilities in Spring 2.5. The tutorial does not include the annotations such as 

@Transactional, @Required and @PersistenceContext / @PersistenceUnit. These were introduced as 

earlier as Spring 2.0 itself.
</p>

<p>
The @Transactional annotation can be used to configure transactional setting for the public 

methods of a class or interface. The transactional behavior of the class annotated with 

@Transactional can be easily enabled with the <tx:annotation-driven/> element in the xml 

configuration file.
</p>

<p>
The @Required annotation is used to specify that the value of a bean property is required to be 

dependency injected. That means, an error is caused if a value is not specified for that 

property.
</p>

<p>
JPA integration is supported by Spring with the @PersistenceContext and @PersistenceUnit 

annotations for injecting the EntityManager and EntityManagerFactory respectively. 
</p>

</body>
</html>

]]>

</content>
</entry>

</feed>