Sobes.tech
Middle

If beans are declared via @Configuration and @Bean, how does @Qualifier work and what is the bean's name?

sobes.tech AI

Answer from AI

When beans are declared using @Configuration and @Bean, Spring creates them with names corresponding to the name of the method that returns the bean. For example:

@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}

In this case, the bean name is myService.

The @Qualifier annotation is used to specify which bean to inject when there are multiple beans of the same type in the context. For example:

@Bean
public MyService myService1() { ... }

@Bean
public MyService myService2() { ... }

@Autowired
@Qualifier("myService2")
private MyService service;

Here, @Qualifier tells Spring to inject the bean named myService2.

Thus, @Qualifier works by the bean name, which by default matches the name of the method declaring the bean, unless explicitly specified otherwise via the name parameter in @Bean.

If beans are declared via @Configuration and @Bean… - sobes.tech