I have the following configuration, where I have two Spring beans with the same name from two different configuration classes.
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class OtherRestTemplateConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
And I introduce (and use) this bean as follows:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; @Component public class SomeComponent { @Autowired private RestTemplate restTemplate; }
Now, my question is: why doesn't Spring complain about having multiple beans with the same name? I would expect an exception here and should add the @Primary annotation to make sure the correct one is used.
On the side of the note: even if I add @Primary , it still doesn't always enter the correct one.
java spring spring-boot
wjans
source share