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.
@Primary Works Internally:@Bean methods, or implicitly via @Component, @Service, @Repository, and similar annotations.@Primary annotation, Spring gives preference to that bean when injecting it into dependent classes.@Primary. This priority information is stored in the DefaultListableBeanFactory (or similar container), where Spring tracks which bean is "primary" for a given type.@Primary. If found, that bean is injected.@Primary, and no explicit bean is specified using @Qualifier, Spring will throw a NoUniqueBeanDefinitionException, as it cannot determine which bean to inject.@Qualifier:
@Qualifier is used, it overrides @Primary. That is, @Qualifier explicitly tells Spring which bean to inject, even if @Primary is present on another bean.@Primary for general use.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.
@Primary:@Primary.@Primary annotation.@Primary or no @Qualifier, and multiple beans are found, Spring throws an exception indicating ambiguity.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: