spring

Spring @Autowired Annotation Example

In this article, we will explain the Spring autowired Annotation.

1. Introduction

Spring framework provides autowiring of beans using the XML configuration but the developers decided to go a step ahead and provide the autowired annotation. This tutorial will explore the Spring-specific annotation (i.e. @Autowired) that will automatically inject the dependent beans.

1.1 Spring Framework

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

1.2 @Autowired annotation in spring

The @Autowired annotation in spring automatically injects the dependent beans into the associated references of a POJO class. This annotation will inject the dependent beans by matching the data-type (i.e. Works internally as Autowiring byType). Developers can apply the @Autowired annotation to the following:

  • @Autowired on property
  • @Autowired on the setter method
  • @Autowired on constructor

1.2.1 Activate @Autowired annotation

To activate this annotation in spring, developers will have to include the <context:annotation-config /> tag in the configuration file. Below snippet shows how to include this tag in the configuration file:

Code Snippet

<beans 
    //...
    xmlns:context="http://www.springframework.org/schema/context"
    //...
    xsi:schemaLocation="http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- To activate the @Autowired annotation in spring -->
    <context:annotation-config />
    
</beans>

In addition, the same can also be achieved by specifying the bean definition of the AutowiredAnnotationBeanPostProcessor class in the configuration file. Below snippet shows how to include the object this class in the configuration file:

Code Snippet

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    
</beans>

1.2.2 Using @Qualifier for dependency resolution

Developers at present knew that if they are using Autowiring ‘byType’ mode than an ambiguity exception is thrown at runtime if there are two or more beans for the same class type. In this case, spring will not be able to choose the correct bean definition for the injection purpose. Thus, to resolve this spring developer introduced the @Qualifier annotation.

The @Qualifier annotation controls, which bean should be Autowired on a field. Let us understand this with the help of a quick example. Consider the following bean configuration having two similar employee beans.

sample_spring_config.xml

<beans ....>

	<context:annotation-config />

	<bean id="employee1" class="com.spring.pojo.Employee">
		<property name="name" value="Jane" />
		<property name="age" value="27" />
	</bean>
	
	<bean id="employee2" class="com.spring.pojo.Employee">
		<property name="name" value="Daniel" />		
		<property name="age" value="29" />
	</bean>
	
	<bean id="company" class="com.spring.pojo.Company">
		<property name="name" value="Test" />		
	</bean>
</beans>

Now, how will spring framework know which bean to wire? To fix this, developers can use the @Qualifier annotation to autowire a particular bean i.e.

Company.java

public class Company {
	
	@Autowired
	@Qualifier(value="employee1")
	private Employee emp;
	
	......
}

This will resolve the ambiguity exception as it means that only the employee1 bean is autowired into the Company’s emp property.

Note: The @Qualifier annotation is activated by specifying the <context:annotation-config /> tag in the spring configuration file.

Now, open up the Eclipse IDE and let us see how to implement this annotation (using the property-based approach) in the spring framework!

2. Spring autowired Annotation Example

Here is a systematic guide for implementing this tutorial in the spring framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, MySQL and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

spring autowired - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Create a Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select the project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

spring autowired - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

spring autowired - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring</groupId>
	<artifactId>SpringAutowiredAnnotation</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:

pom.xml

<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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring</groupId>
	<artifactId>SpringAutowiredAnnotation</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Country Model

This POJO class contains a single field for demonstrating the use of @Autowired annotation. Add the following code to it:

Country.java

package com.spring.pojo;

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

public class Country {

	private String countryName;

	@Autowired	
	private Capital capital;

	public String getCountryName() {
		return countryName;
	}

	public void setCountryName(String countryName) {
		this.countryName = countryName;
	}

	public Capital getCapital() {
		return capital;
	}

	public void setCapital(Capital capital) {
		this.capital = capital;
	}

	@Override
	public String toString() {
		return "Country [countryName=" + countryName + ", capital=" + capital.toString() + "]";
	}
}

3.2.2 Implementation of Country2 Model

This POJO class contains a single field for demonstrating the use of @Autowired and @Qualifier annotations. Add the following code to it:

Country2.java

package com.spring.pojo;

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

public class Country2 {

	private String countryName;

	@Autowired
	@Qualifier(value="myCapital2")
	private Capital capital;

	public String getCountryName() {
		return countryName;
	}

	public void setCountryName(String countryName) {
		this.countryName = countryName;
	}

	public Capital getCapital() {
		return capital;
	}

	public void setCapital(Capital capital) {
		this.capital = capital;
	}

	@Override
	public String toString() {
		return "Country [countryName=" + countryName + ", capital=" + capital.toString() + "]";
	}
}

3.2.3 Implementation of Capital Model

This POJO class contains a single field for demonstrating the bean injection in the spring framework. Add the following code to it:

Capital.java

package com.spring.pojo;

public class Capital {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Capital [name=" + name + "]";
	}
}

3.2.4 Implementation of Utility Class

The implementation class will get the bean definition from the context file and performs the particular type of autowiring. Add the following code to it:

AppMain.java

package com.spring;

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

import com.spring.pojo.Country;
import com.spring.pojo.Country2;

public class AppMain {
	
	private static void autowired(String file) {

		ApplicationContext ac = new ClassPathXmlApplicationContext(file);
		if (file.equalsIgnoreCase("autowired.xml")) {
			Country country = ac.getBean("myCountry", Country.class);
			System.out.println(country.toString());
		} else {
			Country2 country = ac.getBean("myCountry", Country2.class);
			System.out.println(country.toString());
		}
	}

	public static void main(String[] args) {

		int choice = Menu.displayMenu();

		switch (choice) {
		case 1:
			System.out.println("'Autowired annotation' selected");
			autowired("autowired.xml");
			break;
		case 2:
			System.out.println("'Autowired with Qualifier annotation' selected");
			autowired("autowired-qualifier.xml");
			break;
		default:
			System.err.println("Invalid choice.");
		}
	}
}

3.3 Configuration Files

Let us write all the configuration files involved in this application.

3.3.1 Autowired

A typical bean configuration file for understanding the @Autowired annotation will look like this:

autowired.xml

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

	<!-- Used to activate the @Autowired annotation in Spring -->
	<context:annotation-config />

	<bean id="myCapital" class="com.spring.pojo.Capital">
		<property name="name" value="Delhi" />
	</bean>

	<bean id="myCountry" class="com.spring.pojo.Country">
		<property name="countryName" value="India" />
	</bean>
</beans>

3.3.2 Autowired with Qualifier

A typical bean configuration file for understanding the @Autowired and @Qualifier annotations will look like this:

autowired-qualifier.xml

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

	<!-- Used to activate the @Autowired annotation in Spring -->
	<context:annotation-config />

	<bean id="myCapital1" class="com.spring.pojo.Capital">
		<property name="name" value="The Hague" />
	</bean>
	
	<bean id="myCapital2" class="com.spring.pojo.Capital">
		<property name="name" value="Amsterdam" />
	</bean>

	<bean id="myCountry" class="com.spring.pojo.Country2">
		<property name="countryName" value="Netherlands" />
	</bean>
</beans>

4. Run the Application

To execute the application, right-click on the AppMain class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

spring autowired - Run the Application
Fig. 5: Run the Application

5. Project Demo

The code shows the Autowired menu as shown in Fig. 6. Users can select the particular option to briefly understand the @Autowired annotation in the spring framework.

Spring @Autowired Annotation
Fig. 6: Spring @Autowired annotation

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Summary

This post defines the @Autowired in the spring framework and helps developers understand the basic configuration required to achieve this.

  • @Autowired annotation is a spring annotation and is Autowiring byType
  • Activated by specifying the <context:annotation-config /> tag or the object of AutowiredAnnotationBeanPostProcessor class in the configuration file
  • The required attribute of the @Autowired annotation makes the bean injection mandatory
  • It cannot be used to inject the references into the BeanPostProcessor or the BeanFactoryPostProcessor classes

Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of the Spring autowired annotation for beginners.

Download
You can download the full source code of this example here: Spring @Autowired Annotation Example

Last updated on May 03rd, 2021

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button