Using Annotations to Autowire beans in the Spring Framework

The new features of the Java 5 framework include Annotations. Annotations is a sort of meta-data about classes. These new Java 5 feature allow the developer to describe additional information about java classes methods and fields. This additional metadata can be used to generate boilerplate code used to configure the application at runtime.

Spring Framework and XML

If you have worked with the spring framework long enough you get to know that a lot of configuration is xml based. While this is great for very large application it can get to be a hassle for small project. Also if you are creating a rapid proto-type you want your codeing experience to be free-flowing. You dont really want to create a class and then have to write xml code inject it into another class.

In the following tutorial we will cover the basics of how to create a simple standalone spring application that will auto-wire itself with very little xml configuration. Spring XML configuration will be 2-3 lines of code  (not including the header).

Start a new project

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart

Answer the rest of the questions like this:
Group ID: com.test
Artifact Id: springAnnotation

cd springAnnotation

We first start out by creating a plain old Java Application in the eclipse project. You can go ahead and create one and put a Maven 2 pom.xml file seen below.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">


Regenerate the project

Regenerate the project in eclipse by typing: mvn eclipse:clean eclipse:eclipse

Annotation Based configuration

Create the resources folder if it does not exist. and create the applicationContext.xml file.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"





        <context:component-scan base-package="com.test"/>



Indicates that this field is required to be injected. If this bean did not get injected by the time the injection step completes then the container shuts down and prints an error message.

@Autowired or @Resource (JSR-250) method

Used on setters to auto inject dependencies into beans. Prefer using @Resource because it is a Java Standard.


Used for fine tuning of what gets selected for injection.

Example Application


package com.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;

public class ClassA {
        private IClassB classB;

        public IClassB getClassB() {
                return classB;
        public void setClassB(IClassB classB) {
                this.classB = classB;



package com.test;

import org.springframework.stereotype.Component;

public class ClassB implements IClassB {

        public void testMethod() {
                System.out.println("\n\n\nSpring Annotations are Easy!!!\n\n\n");


package com.test;

public interface IClassB {
        public abstract void testMethod();

The following is a test class that will print the results to the console.


package com.test;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.CollectionUtils;

public class AppTest extends TestCase {
        public AppTest(String testName) {

        public static Test suite() {
                return new TestSuite(AppTest.class);

        public void testApp() {
                ApplicationContext context = new ClassPathXmlApplicationContext(
                ClassA classA = (ClassA) context.getBean("classAA");

Run the test

At the root directory for the project type the following.

mvn test

This should print out the following to the console:

[org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalRequiredAnnotationProcessor, classAA, classB]

Spring Annotations are Easy!!!

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.338 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 second
[INFO] Finished at: Sun Jun 06 22:03:36 EDT 2010
[INFO] Final Memory: 15M/159M
[INFO] ------------------------------------------------------------------------

Component Scanning

In the previous section we reviewed how to inject beans that are already defined in the application Context injected into new beans using @Autowired or @Resource.

In this section we will go over how those beans got into the application context in the first place.

The magic starts with specifying a comma separated list of packages that will be scanned for Annotations. Put the following line into the spring configuration file.

<context:component-scan base-package="test"/>

The system will scan the test package for components that should be added to the application context. There is no need to define them in an xml file. You do need to put the following annotation at the class level so they get recognized.

Component Scan Annotations

@Repository – this was added as part of Spring 2.0 to indicate that this class serves the role of a datamanager or DAO.
@Component – this annotation indicates that this class is a general purpose spring managed bean. The @Repository, @Service, and @Controller are specializations of this base bean. You can always use @Component for all beans, but its not a good idea.
@Service – this annotation indicates that this is a class that contains Business Logic and serves as the Service/Model bean.
@Controller – Typically indicates that this class is used as a Controller in a Web Application.

Naming Component Scanned Beans

By default unless other wise specified a bean name will be the same name as the class however the first letter will not be capatalized. For example the following class will appear as movieFinderImpl

public class MovieFinderImpl implements MovieFinder {

If you want to specify a custom name for a bean all you need to specify is the following and the bean will be known as specialMovieFinder in the spring container.

public class MovieFinderImpl implements MovieFinder {

Constructor Injection

If your beans use constructor injection instead of setter injection you can still use annotations. Just use the @Qualifier annotation for each constructor parameter.

public class ClassA {
    private IClassB classB;

    public IClassB getClassB() {
        return classB;

    public ClassA(@Qualifier("classB") IClassB classB) {
        this.classB = classB;

Scalar Values

At this moment it does not look like you can specify scalar values based on annotations. But after a few minutes of thinking this thru, why would you want to? You can always set the scaler value in the constructor or where you are defining the attributes. With spring 3 you may use @Value annotation.

This site is a collaborative effort! The complete text and sourcecode for this is available on GitHub. Corrections and enhancements are welcome, please make the change and submit a pull request in the comment area below.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

October 2009
« Sep   Nov »

Blog Stats

  • 846,580 hits

%d bloggers like this: