Sobes.tech
Middle+

If you have two beans, how do you choose one by default?

sobes.tech AI

Answer from AI

In the Spring Framework, if you have two beans of the same type and need to select one as the default, you can use the @Primary annotation on the bean that should be chosen by default.

Example:

@Configuration
public class AppConfig {

    @Bean
    @Primary
    public Service serviceOne() {
        return new ServiceImplOne();
    }

    @Bean
    public Service serviceTwo() {
        return new ServiceImplTwo();
    }
}

In this example, if a Service type bean is injected somewhere in the code without specifying a particular name, Spring will choose serviceOne because it is marked with @Primary.

Alternatively, you can use @Qualifier to explicitly specify the desired bean during injection.

If you have two beans, how do you choose one by… - sobes.tech