Spring Boot不会抱怨两个同名的bean [英] Spring boot not complaining about two beans with the same name

查看:283
本文介绍了Spring Boot不会抱怨两个同名的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下配置,其中有两个不同配置类中的两个名称相同的Spring Bean.

I'm having 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();
    }
}

我正在像这样注入(和使用)这个bean:

And I am injecting (and using) this bean like this:

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;

}

现在,我的问题是:为什么Spring不抱怨拥有相同名称的多个bean?我希望在这里出现异常,并且必须添加@Primary批注以确保正在使用正确的批注.

Now, my question is: why is Spring not complaining about having multiple beans with the same name? I would expect an exception here and having to add a @Primary annotation to make sure that the correct one is being used.

附带说明:即使我添加了@Primary,它仍然不能总是注入正确的内容.

On a side note: even if I add @Primary it is still not always injecting the correct one.

推荐答案

其中一个bean覆盖了另一个bean,因为您使用了相同的名称.如果@paweł-głowacz建议使用不同的名称,则使用

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会抱怨,因为它发现两个具有相同RestTemplate类型的bean,并且不知道使用哪个bean.然后将@Primary应用于其中之一.

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.

此处有更多说明: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆