大家好!我試圖解決這個問題很長一段時間。
有一個非常簡單的spring boot test
public class ApplicationTest {
@Test
void testContext() {
SpringApplication.run(Application.class);
}
}
還有幾個豆子...
@Service
@ConditionalOnBean(CommonService.class)
@RequiredArgsConstructor
public class SimpleHelper {
...
@Service
@RequiredArgsConstructor
@ConditionalOnBean(CommonFeignClient.class)
public class CommonService {
...
@FeignClient(
name = "CommonClient",
url = "localhost:8080"
)
public interface CommonFeignClient {
主要課程看起來像
@SpringBootApplication
@EnableFeignClients(clients = AnotherFeignClient.class)
public class Application {
當 spring 應用程式啟動時,一切正常。SimpleHelper 沒有創建。但是在 spring boot 測驗中拋出例外:
原因:org.springframework.beans.factory.UnsatisfiedDependencyException:創建名稱為“simpleHelper”的 bean 在 URL [...] 中定義時出錯:通過建構式引數 0 表示的不滿足依賴項;嵌套例外是 org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有“foo.bar.CommonService”型別的合格 bean 可用:預計至少有 1 個有資格作為自動裝配候選者的 bean。依賴注釋:{}
請幫忙,我不明白發生了什么=)
Spring Boot 版本是 2.3.0.RELEASE。
uj5u.com熱心網友回復:
要@ConditionalOnBean正確使用,CommonService需要是自動配置類或由自動配置類定義為 bean,而不是通過組件掃描找到的服務。這確保了在CommonService評估條件之前已經定義了有條件的 bean。注釋的 javadoc中描述了對此的需求:
該條件只能匹配到目前為止已由應用程式背景關系處理的 bean 定義,因此,強烈建議僅在自動配置類上使用此條件。如果候選 bean 可能由另一個自動配置創建,請確保使用此條件的那個在之后運行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496913.html
