Skip to main content

Annotation based configuration in Spring

Posted by seemarich on November 27, 2007 at 4:14 AM PST

Exploring annotations in Spring 2.5

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.

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.

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

with the help of a simple tutorial.

What you need before you start

You need the following software to try out the tutorial.

Java 5.0

Spring Framework 2.5

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


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

Adding the classes and interfaces for the example

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

or fired.

Let me start with the EmployeeService interface.

package emptest;

public interface EmployeeService {
String hire(String name);

String fire(String name);

Here is a simple class that implements this interface.

public class EmployeeServiceImpl implements EmployeeService {
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;

Stereotype Annotations

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".

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.

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.


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.

public interface EmployeeDao {
    String getMessage(String messageKey);

The implementing class EmployeeDaoImpl uses the @Repository annotation.

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);

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

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

creates the SimpleJdbcTemplate object.

Simplified Configuration

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


<beans xmlns=""
" title="">
<context:annotation-config />
<context:component-scan base-package="emptest" />
<aop:aspectj-autoproxy />

<context:property-placeholder location="" />

<bean id="dmdataSource"
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

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

element is used to automatically register all of Spring's

standard post-processors for annotation-based configuration. The

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

element can be omitted.

The properties for the data source are taken from the file in the classpath. The

property placeholders are configured with the element.

The element is used to enable @AspectJ support in Spring.


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.

public class TraceLogger {
private static final Logger LOG = Logger.getLogger(TraceLogger.class);

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

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


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.

@Qualifier and @Resource

Suppose there is one more DataSource configuration in the spring context file as follows.

<bean id="jndidataSource"
<property name="jndiName" value="jdbc/test" />

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”.

public void createTemplate(@Qualifier("dmdataSource") DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);

JSR-250 Annotations

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


@Resource(name = "dmdataSource")
public void createTemplate(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);

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.

public void initialize() {
jdbcTemplate.update("create table messages (messagekey varchar(20), message

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')");

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

Unit Testing

Before testing the service implementation, I provided the database configuration details in the file as follows.


Here is the class I wrote for unit testing.

public class EmployeeServiceImplTests extends
AbstractDependencyInjectionSpringContextTests {
private EmployeeService employeeService;

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 =;
assertEquals(name + ", " + "Sorry! You are fired", message);

public void setEmployeeService(EmployeeService employeeService) {
this.employeeService = employeeService;


You can download the source code for this tutorial



The inputs from the following sources were very helpful in writing this tutorial.

Rod Johnson's

article on Spring 2.5

Spring 2.5



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.

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 element in the xml

configuration file.

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


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

annotations for injecting the EntityManager and EntityManagerFactory respectively.

Related Topics >>


Annotation based

great post..

i also found a spoon fed tutorial using @Required annotation

hope it helps