we use @Primary
to give higher preference to a bean when there are multiple beans of the same type.
Example
@Configuration
public class Config {
@Bean
public Employee JohnEmployee() {
return new Employee("John");
}
@Bean
public Employee TonyEmployee() {
return new Employee("Tony");
}
}
Spring throws NoUniqueBeanDefinitionException if we try to run this code. To access beans with the same type we usually use @Qualifier(“beanName”) annotation.
We apply it at the injection point along with Autowired. In our case, we select the beans at the configuration phase so Qualifier can't be applied here.
Using @Primary
with Beans
@Configuration
public class Config {
@Bean
public Employee JohnEmployee() {
return new Employee("John");
}
@Bean
@Primary
public Employee TonyEmployee() {
return new Employee("Tony");
}
}
Now, let's start the application context and get the Employee bean from it:
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext(Config.class);
Employee employee = context.getBean(Employee.class);
System.out.println(employee);
When we run the applcation, it will print:
Employee{name='Tony'}