Spring autowired annotation example

The Spring autowired annotation example shows you how to configure bean dependency injection using annotation. In the previous example, you can use XML to describe a bean wiring, and now you can use annotation to configure the bean wiring. In case, a bean wiring is configured both with annotation and XML, the XML will override the annotation configuration. Because Spring container will perform annotation injection before XML injection.

Let’s begin:

Application Data Access Object(DAO)

First of all, We create the Data Access Object(DAO) with a simple class HelloSpringDAO.

1

2

3

4

5

6

7

8

packagecom.javabycode.spring;

publicclassHelloSpringDAO{

publicStringgetMsg(){

return"Spring autowired annotation example";

}

}

Application Service and Injecting Bean using Spring annotation Configuration Before we can use the spring annotation configuration we must enable it in our spring configuration file(spring-config.xml) by add this line

1

<context:annotation-config/>

Then we use the @Autowired to inject a bean automatically. I notice that the @Autowired is used at method, constructor, or field level to mark the component must be automatically injected by Spring. Let’s see the below snippet code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

packagecom.javabycode.spring;

import org.springframework.beans.factory.annotation.Autowired;

publicclassHelloSpringService{

@Autowired

privateHelloSpringDAO dao;

publicvoidsayHello(){

System.out.println(dao.getMsg());

}

publicvoidsetDao(HelloSpringDAO springDAO){

this.dao=springDAO;

}

}

Spring Configuration Don’t forget enable Spring annotation configuration because it is not turned on by default as it is mentioned above by using element. This will activate annotation driven configuration. Then we add two bean definitions so we can wire them together. Let’s see the detail spring configuration(spring-config.xml) like below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/beans

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

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

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

<description>

Spring autowired annoation example.

</description>

<context:annotation-config/>

<bean class="com.javabycode.spring.HelloSpringService"/>

<bean class="com.javabycode.spring.HelloSpringDAO"/>

</beans>

Demo Spring application In this Spring autowired annoation example, we create main class and load all the bean definitions using the constructor of the ApplicationContext. This context will bootstrap the Spring application.