Spring @Qualifier annotation tutorial
last modified October 18, 2023
Spring @Qualifier annotation tutorial shows how to use @Qualifier to differentiate beans in a Spring application.
Spring is a popular Java application framework for creating enterprise applications.
Spring @Qualifier annotation
The @Qualifier annotation helps disambiguate bean references when Spring
would otherwise not be able to do so.
Spring @Qualifier example
The application has different types of message beans. We differentiate between them
with @Qualifier.
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ ├───bean
│ │ │ IMessage.java
│ │ │ Info.java
│ │ │ Warning.java
│ │ └───service
│ │ MessageProducer.java
│ └───resources
│ logback.xml
└───test
└───java
This is the project structure.
<?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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>qualifierannotation</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>com.zetcode.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
In the pom.xml file, we have basic Spring dependencies spring-core
and spring-context and logging logback-classic dependency.
The exec-maven-plugin is used for executing Spring application from the
Maven on the command line.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.springframework" level="ERROR"/>
<logger name="com.zetcode" level="INFO"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
The logback.xml is a configuration file for the Logback logging library.
package com.zetcode.bean;
public interface IMessage {
String getMessage();
}
The IMessage interface has one method declaration.
package com.zetcode.bean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("info")
public class Info implements IMessage {
@Override
public String getMessage() {
return "This is an information message";
}
}
The first implementation of the interface gives an information message.
The @Qualifier is used to identify the bean.
package com.zetcode.bean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
@Qualifier("warning")
public class Warning implements IMessage {
public String getMessage() {
return "This is a warning message";
}
}
The second implementation gives a warning message. It is also named with
the @Qualifier.
package com.zetcode.service;
import com.zetcode.bean.IMessage;
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.stereotype.Service;
@Service
public class MessageProducer {
private static final Logger logger = LoggerFactory.getLogger(MessageProducer.class);
@Autowired
@Qualifier("info")
private IMessage infoMessage;
@Autowired
@Qualifier("warning")
private IMessage warningMessage;
public void produce() {
logger.info("{}", infoMessage.getMessage());
logger.warn("{}", warningMessage.getMessage());
}
}
The MessageProducer injects two IMessage beans. To differentiate between them,
we use @Qualifier annotations.
package com.zetcode;
import com.zetcode.service.MessageProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.zetcode.bean;com.zetcode.service")
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
logger.info("Application starting");
try (var ctx = new AnnotationConfigApplicationContext(Application.class)) {
var messageProducer = (MessageProducer) ctx.getBean("messageProducer");
messageProducer.produce();
}
}
}
This is the main application class. It retrieves the messageProducer bean
and call its produce method.
$ mvn -q exec:java 10:50:03.309 [com.zetcode.Application.main()] INFO com.zetcode.Application - Application starting 10:50:03.574 [com.zetcode.Application.main()] INFO com.zetcode.service.MessageProducer - This is an information message 10:50:03.574 [com.zetcode.Application.main()] WARN com.zetcode.service.MessageProducer - This is a warning message
We run the application.
In this article we have worked with Spring's @Qualifier annotation.
Author
List all Spring tutorials.