關於spring boot自動注入出現Consider defining a bean of type 'xxx' in your configuration問題解決方案
轉載自:
搭建完spring boot的demo後自然要實現自動注入來體現spring ioc的便利了,但是我在實施過程中出現了這麼一個問題,見下面,這裡找到解決辦法記錄下來,供遇到同樣的問題的同僚參考
Description: Field helloService in com.example.demo.service.TestController required a bean of type 'com.example.service.HelloService' that could not be found. Action: Consider defining a bean of type 'com.example.service.HelloService' in your configuration.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
然後我又看了下自己寫的幾個類以及註解見下面,感覺寫的沒有問題啊 控制器 TestController 介面HelloService 介面對應的實現類HelloServiceImpl 根據英文的提示是在配置中找不到一個指定自動注入型別的bean,經過多方排查得出結論: 正常情況下加上@Component註解的類會自動被Spring掃描到生成Bean註冊到spring容器中,既然他說沒找到,也就是該註解被沒有被spring識別,問題的核心關鍵就在application類的註解SpringBootApplication上
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters={@Filter(type=CUSTOM, classes={TypeExcludeFilter.class}), @Filter(type=CUSTOM, classes={AutoConfigurationExcludeFilter.class})}) @Target(value={TYPE}) @Retention(value=RUNTIME) @Documented @Inherited
- 1
- 2
- 3
- 4
- 5
- 6
- 7
至此,得出兩種解決辦法: 1 .將介面與對應的實現類放在與application啟動類的同一個目錄或者他的子目錄下,這樣註解可以被掃描到,這是最省事的辦法 2 .在指定的application類上加上這麼一行註解,手動指定application類要掃描哪些包下的註解,見下圖 通過這兩種方式,那個找不到指定Bean的錯誤就成功解決了。。。。。那麼這篇就這樣吧 PS:控制器Controller也要放在與application同級或者子目錄下,道理大致一樣
--------------------- 本文來自 夢嵐如雪 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/a532672728/article/details/77702772?utm_source=copy