Suppose that I have two beans defined like this:
@Configuration
public class ConfigurationA {
@Bean
@Qualifier("restTemplateA")
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//setting some restTemplate properties
return restTemplate;
}
}
@Configuration
public class ConfigurationB {
@Bean
@Qualifier("restTemplateB")
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
//setting some restTemplate properties
return restTemplate;
}
}
When I autowire restTemplate without providing @Qualifier, which bean will be injected? How is it decided?
@Service
public class someClass {
@Autowired
private RestTemplate restTemplate;
}
Note:When I test, one of the bean is injected. It didn't lead any exception.
Note2: I know I can use @Qualifier to inject the bean that I want or I can use @Primary to avoid ambiguity. But I just want to understand why it is valid for Spring.
Note3: When I changed the method name in class ConfigurationB to restTemplateB, bean defined in ConfigurationA is injected. Again it didnt' lead any exception.
I tried this in Spring Boot version 1.4.4
@Bean( name = "firstRestTemplateName" )
then when autowiring into your service add@Qualifier( "firstRestTemplateName" )
– RobOhRob@Primary
to make it the default – RobOhRob