[英]Bean name resolution in Spring using @Bean and @Qualifier annotations
我剛剛發現了一種我無法理解的 Spring 行為。 我正在使用 Spring Boot 1.5.x。
在一個配置類中,我聲明了兩個不同的 bean。
@Configuration
class Config {
@Bean("regularRestTemplate")
public RestTemplate regularRestTemplate(String toLog) {
return new RestTemplateBuilder().setConnectTimeout(100)
.setReadTimeout(100)
.additionalInterceptors((request, body, execution) -> {
log.info("Inside the interceptor {}", toLog);
return execution.execute(request, body);
})
.build();
}
@Bean("exceptionalRestTemplate")
public RestTemplate regularRestTemplate() {
return new RestTemplateBuilder().setConnectTimeout(100)
.setReadTimeout(100)
.build()
}
}
然后,我有一個類應該使用名為exceptionalRestTemplate
的 bean。
@Component
class Client {
private RestTemplate restTemplate;
@Autowired
public Client(@Qualifier("exceptionalRestTemplate") RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
// Code that uses the injected rest template
}
由於我使用@Qualifier
注釋指定了要注入的 bean 的名稱,因此我希望 Spring 注入名為exceptionalRestTemplate
的 bean。 但是,在注入過程中實際上使用了名為regularRestTemplate
的bean。
事實證明,問題在於在配置類中聲明 bean 的方法的名稱。 兩者都歸類為regularRestTemplate
。 更改第二個方法名,解決問題。
我的問題是,為什么? 我知道 Spring 使用用@Bean
或@Component
、 @Service
等注釋的類和方法的名稱...注釋來為解析映射中的 Java 對象命名。 但是,我認為在這些注釋中命名會覆蓋這種行為。
有人告訴我這是怎么回事嗎?
bean 限定符和 bean 名稱是不同的含義。 您對 new bean 進行了限定,但試圖覆蓋它(參數無關緊要)。 在您的應用程序中,您不能覆蓋 bean,因此您只有第一個 bean。
你可以檢查這個“理論”。 在您的配置中添加一個參數
spring.main.allow-bean-definition-overriding=true
並再次啟動您的應用程序。 在那之后,您將只有第二個豆子。
這是對碰撞的解釋。 但解決方案是將 bean 分離為不同的配置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.