How internally Primary Annotation works

In Spring Boot, @Primary is used to indicate a primary bean among multiple candidate beans of the same type. When Spring's dependency injection mechanism encounters multiple beans of the same type and does not know which one to inject, it will inject the bean marked as @Primary. Let’s dive into how @Primary works internally in Spring.

How @Primary Works Internally:

  1. Bean Definition Phase:
  2. Primary Bean Resolution:
  3. Dependency Injection Phase:
  4. Interaction with @Qualifier:

Example:

Let’s say you have two beans of the same type:

@Configuration
public class AppConfig {

    @Bean
    public DataSource myDataSource1() {
        return new DataSource("DataSource1");
    }

    @Primary
    @Bean
    public DataSource myDataSource2() {
        return new DataSource("DataSource2");
    }
}

When Spring needs to inject a DataSource bean, and no @Qualifier is specified, Spring will inject myDataSource2 because it is marked with @Primary.

Flow of Bean Injection with @Primary:

  1. Bean Creation: Spring creates beans according to the configuration.
  2. Bean Registration: Beans are registered in the Spring container with metadata, including any annotations like @Primary.
  3. Injection Decision:
  4. Fallback: If there’s no @Primary or no @Qualifier, and multiple beans are found, Spring throws an exception indicating ambiguity.

Behind the Scenes:

Internally, the process involves Spring's bean resolution mechanism. This mechanism is part of the AutowireCandidateResolver within the DefaultListableBeanFactory. When determining the eligible beans for injection, Spring does the following: