Skip navigation

seemarich

1 post

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

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

@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;
    }
}

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.

@autowired

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.

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



 

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


<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">
    <context:annotation-config />
    <context:component-scan base-package="emptest" />
    <aop:aspectj-autoproxy />

    <context:property-placeholder location="classpath:jdbc.properties" />

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

Now let me explain the new configurations in the above Spring context file. The <context:annotation-config /> element is used to automatically register all of Spring's standard post-processors for annotation-based configuration. The <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 <context:annotation-config/> element can be omitted.

The properties for the data source are taken from the jdbc.properties file in the classpath. The property placeholders are configured with the <context:property-placeholder> element.

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

@Aspect

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.

@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]);
    }

}

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"
    class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName" value="jdbc/test" />
</bean>

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

Filter Blog

By date: