Home » Spring » Spring Autowiring @Qualifier Tutorial

Spring Autowiring @Qualifier Tutorial

Introduction

As we know the @Autowire annotation is the most frequent way to inject the dependencies in Spring. By default, the @Autowire resolve dependencies by type. This will works fine until we have only one bean with the same type. Sometimes you might have more than one Bean of the same type and if you do not explicitly specify which one you would like to autowire, you will get an NoUniqueBeanDefinitionException when starting up your application.

Spring @Qualifier will be used to differentiate bean of same type.

This annotation helps fine-tune annotation-based autowiring. There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using @Qualifier annotation along with the @Autowired annotation.

This annotation will help @Autowired annotations to choose one of the dependency.

Let’s have a look at an example which will work very well if @Qualifier annotation is used together with @Autowired and will throw an NoUniqueBeanDefinitionException if the @Qualifier annotation is not used.

How to differentiate between two Person beans

In our application, we have two beans of Person type: Student and Teacher. We use the @Qualifier annotation to distinguish between them.

Project Structure

qualifier example


We have developed a sample spring boot application for the demo. Files used in the application is given below.

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.jwt.spring.demo</groupId>
	<artifactId>spring-qualifier-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-qualifier-example</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

pom.xml of project is given above. The spring-boot-starter is the core starter that includes auto-configuration support, logging, and YAML. The application is packaged into a JAR file.

person.java

Let us define an interface that defines the Person type. This interface has only one method information(), which will return String.

package com.jwt.spring.demo.model;

public interface Person {
	
	String information();

}

Student.java

package com.jwt.spring.demo.model;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("student")
public class Student implements Person {

	@Override
	public String information() {
		return "Student Information";
	}

}

In the above Student class. Student inherits from Person. @Component is a basic Spring annotation that allows Student to be detected by Spring containter. The @Qualifier("student") uniquely identifies this bean with the "Student" string.


Teacher.java

package com.jwt.spring.demo.model;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
@Qualifier("teacher")
public class Teacher implements Person {

	@Override
	public String information() {
		return "Teacher Information";
	}

}

In the above class We defined another bean called Teacher. This bean is also identified with the @Qualifier("teacher") annotation.


Test.java

package com.jwt.spring.demo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import com.jwt.spring.demo.model.Person;

@Component
public class Test implements CommandLineRunner {
	
	 private static final Logger logger = LoggerFactory.getLogger(Test.class);
	 
	 @Autowired
	 @Qualifier("student")
	 private Person p1;
	 
	 @Autowired
	 @Qualifier("teacher")
	 private Person p2;
	 

	@Override
	public void run(String... args) throws Exception {
		
		logger.info("Student info: {}", p1.information());
		logger.info("Teacher info: {}", p2.information());

	}

}

The CommandLineRunner interface indicates that a bean should run when it is contained within a SpringApplication. It can be used to create command line applications in Spring Boot.

@Component
public class MyRunner implements CommandLineRunner {

The CommandLineRunner is also a Spring bean and is decorated with the @Component annotation. It will auto-detected by Spring container.

@Autowired
@Qualifier("student")
private Person p1;

In the above code snippet we inject a Person bean into the p1 field. The @Qualifier("student") specifies that it is a Student bean.

@Autowired
	 @Qualifier("teacher")
	 private Person p2;

Similarly, we injected the Teacher bean into the p2 field.


SpringQualifierExampleApplication.java

package com.jwt.spring.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringQualifierExampleApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringQualifierExampleApplication.class, args);
	}

}

The SpringQualifierExampleApplication sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

Output:

When you run this application you can see Student Information and Teacher Information in the logs.

qualifier example


The implementation of this simple Spring @Qualifier Annotation Example can be found in the GitHub project – this is an Eclipse based project, so it should be easy to import and run as it is.

GitHub

Previous Next Article

comments powered by Disqus