When you have multiple beans of the same type in Spring Boot and need to handle them, you can use the @Qualifier annotation to specify which bean should be injected. Here’s how to manage this:
@Configuration
public class AppConfig {
@Bean
@Qualifier("bean1")
public MyBean myBean1() {
return new MyBeanImpl1();
}
@Bean
@Qualifier("bean2")
public MyBean myBean2() {
return new MyBeanImpl2();
}
}
Use Primary Beans:
If one bean is the default choice, annotate it with @Primary.
@Bean
@Primary
public MyBean defaultMyBean()
{
return new MyBeanImpl1();
}
@Bean
public MyBean secondaryMyBean()
{
return new MyBeanImpl2();
}
With @Primary, you don’t need to use @Qualifier unless
you specifically want the other bean.
No comments:
Post a Comment