Spring boot does not complain about two beans with the same name

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.

+7
java spring spring-boot
source share
2 answers

One of the beans overrides the other because you are using the same name. If different names were used as @ paweł-głowacz, then if used

 @Autowired private RestTemplate myRestTemplate; 

spring will complain because it finds two beans with the same RestTemplate type and does not know what to use. Then you apply @Primary to one of them.

More explanation here: more

+3
source share

You need to call this beans like this:

 @Configuration public class RestTemplateConfiguration { @Bean(name="bean1") public RestTemplate restTemplate() { return new RestTemplate(); } } 

and

 @Configuration public class OtherRestTemplateConfiguration { @Bean(name="bean2") public RestTemplate restTemplate() { return new RestTemplate(); } } 
0
source share

All Articles