Spring boot not complaining about two beans with the same name

后端 未结 2 1421
余生分开走
余生分开走 2021-02-20 12:43

I\'m having the following configuration where I have two Spring beans with the same name from two different configuration classes.

import org.springframework.con         


        
相关标签:
2条回答
  • 2021-02-20 13:04

    You need to name that beans so:

    @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 讨论(0)
  • 2021-02-20 13:29

    One of the beans is overriding other one because you use same name. If different names were used as @paweł-głowacz suggested, then in case of using

    @Autowired
    private RestTemplate myRestTemplate;
    

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

    More explanation here: more info

    0 讨论(0)
提交回复
热议问题