我有以下配置,其中有两个来自两个不同配置类的同名 Spring bean。
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:
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
注释以确保使用正确的注释。
旁注:即使我添加@Primary
它仍然不总是注入正确的。
其中一个 Bean 会覆盖另一个 Bean,因为您使用相同的名称。如果按照@paweł-głowacz的建议使用了不同的名称,那么在使用的情况下
@Autowired
private RestTemplate myRestTemplate;
spring 会抱怨,因为它发现两个具有相同 RestTemplate 类型的 bean,并且不知道使用哪个。然后你申请@Primary
给其中之一。
更多解释在这里:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)