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.

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

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:

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:

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.

Run the main class above, the console will print the following message.

That’s it on the Spring autowired annotation example.

Spring Annotation Based Configuration Doc

Download complete source code, click link below

spring-autowired-annotation-example.zip (9 downloads)

Leave a Comment


Please share it if you found this useful
Hide Buttons