Spring @Primary Annotation Example

Spring framework provides a mechanism to automatically inject the multiple dependencies of the same data-type. During the process, NoUniqueBeanDefinitionException is thrown indicating that only one candidate bean can be injected. This tutorial will explore the Spring-specific @Primary annotation that automatically gives a higher preference to a particular bean definition.

1. Introduction

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 @Primary annotation in spring

When there are multiple beans of the same data-type, developers use the Spring-specific @Primary annotation that automatically gives the higher preference to a particular bean. This annotation can be used on any class directly or indirectly annotated with the @Component annotation or on methods annotated with the @Bean annotation.

This annotation can also be configured using the primary xml attribute of the <bean /> element. Below snippet shows how to include this tag in the configuration file:

Code Snippet

//. . . . .

<bean id="author1" class="com.spring.pojo.Author" primary="true">
	<property name="fullname" value="Rajesh Kumar" />
	<property name="dob" value="11 December 1982" />
	<property name="country" value="India" />

<bean id="author2" class="com.spring.pojo.Author">
	<property name="fullname" value="Kishore Singh" />
	<property name="dob" value="05 May 1991" />
	<property name="country" value="India" />

// . . . . . .

Now, open up the Eclipse IDE and let us see how to implement this annotation in the spring framework!

2. Spring @Primary 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 @Primary Annotation - 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.

Spring @Primary Annotation - Create a Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select 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 @Primary Annotation - 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 @Primary Annotation - 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:


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

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:


<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">
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Author Model

The model class contains three fields for demonstrating the use of @Primary annotation. Add the following code to it:


package com.spring.pojo;

public class Author {

	private String fullname;	
	private String dob;
	private String country;

	public String getFullname() {
		return fullname;

	public void setFullname(String fullname) {
		this.fullname = fullname;

	public String getDob() {
		return dob;

	public void setDob(String dob) {
		this.dob = dob;

	public String getCountry() {
		return country;

	public void setCountry(String country) {
		this.country = country;

	public String toString() {
		return "Author [fullname=" + fullname + ", dateOfBirth=" + dob + ", country=" + country + "]";

3.2.2 Implementation of Application Configuration

The configuration class defines the bean definition for the model class. Here we are creating multiple beans of the same data-type, so technically spring framework will throw the NoUniqueBeanDefinitionException exception if developers do not give a preference to one of the beans. To achieve this, developers will use the @Primary annotation to give higher preference to a particular bean. Add the following code to it:


package com.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.spring.pojo.Author;

public class AppConfig {

	public Author getAuthor1() {
		System.out.println("getAuthor1() is called");

		Author author = new Author();		
		author.setFullname("Rajesh Kumar");		
		author.setDob("11 December 1982");

		return author;

	public Author getAuthor2() {
		System.out.println("getAuthor2() is called");

		Author author = new Author();		
		author.setFullname("Kishore Singh");		
		author.setDob("05 May 1991");

		return author;

3.2.3 Implementation of Utility Class

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


package com.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.spring.pojo.Author;

public class AppMain {

	public static void main(String[] args) {

		ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

		Author author1 = ac.getBean(Author.class);

		// Closing the application context!
		((AnnotationConfigApplicationContext) ac).close();

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 @Primary Annotation - Run the Application
Fig. 5: Run the Application

5. Project Demo

The code shows the following logs as follows.

Success Logs

getAuthor1() is called
getAuthor2() is called
Author [fullname=Rajesh Kumar, dateOfBirth=11 December 1982, country=India]

Do note, if the @Primary annotation is not defined, the application will throw the exception as shown below.

Error Logs

getAuthor1() is called
getAuthor2() is called
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.spring.pojo.Author' available: expected single matching bean but found 2: getAuthor1,getAuthor2
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveNamedBean(DefaultListableBeanFactory.java:1039)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:339)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1107)
	at com.spring.AppMain.main(AppMain.java:14)

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. Conclusion

This post defines the @Primary in the spring framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of spring @Primary annotation for beginners.

You can download the full source code of this example here: SpringPrimaryAnnotation


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).
Notify of

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

1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
4 years ago


I don’t where I could use it in a real life app?
Any ideas, examples?

Back to top button