You are currently viewing @Primary Annotation in Spring Boot

@Primary Annotation in Spring Boot

The @Primary annotation is used to give a higher preference to a specific bean when multiple beans of the same type exist. This is useful when you have multiple implementations of an interface or multiple beans of the same type, and you want to indicate a default or primary choice.

1. Dependency Setup

Make sure you have the necessary dependencies in your Spring Boot project. At a minimum, you’ll need the spring-boot-starter and spring-boot-starter-test dependencies in your pom.xml (if you’re using Maven) or build.gradle (if you’re using Gradle).

Maven Example:

<!-- pom.xml -->

Gradle Example:

// build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

2. Creating Beans

Let’s create an interface MessageService with two implementations, and then use @Primary to indicate the primary choice.

3. Using @Primary

Now, use @Primary on the preferred implementation, typically where you declare the bean.

In this example, primaryMessageService() is annotated with @Primary, indicating that it’s the primary choice among multiple MessageService implementations.

4. Using the Beans

Now, you can inject MessageService wherever needed, and the @Primary annotated bean will be the default choice.

5. Run the Application

Now, run your Spring Boot application and visit http://localhost:8080/message to see the output.

If you want to switch the primary bean, you can simply remove @Primary from one bean and add it to another. The @Primary annotation makes it easy to control the default behavior when multiple beans of the same type are present in the Spring application context.

Leave a Reply