今天用springboot+mybatis寫一個小demo遇到如下錯誤
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-04-08 14:11:11.359 ERROR 7300 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field dao in cn.niit.controller.DemoController required a bean of type 'cn.niit.TestMapper.TestMapper' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'cn.niit.TestMapper.TestMapper' in your configuration.
Process finished with exit code 1
它說沒有找到這個類,說明這個類沒有注入到spring容器,以為是注解沒有被掃描,然后各種網上搜以及自己各種重啟嘗試,了解到@SpringBootApplication沒有掃描到
正常情況下加上@Component注解的類會自動被Spring掃描到生成Bean注冊到spring容器中,既然他說沒找到,也就是該注解被沒有被spring識別,問題的核心關鍵就在application類的注解SpringBootApplication上 ,@SpringBootApplication這個注解掃描該類同級包下的類以及子包的類
我換包的位置后各種嘗試還是不行,接着再了解到
說是在啟動類上加上@ComponentScan,還是沒能解決,說是@ComponentScan和@SpringBootApplication掃描包覆蓋:
@SpringBootApplication=@Configuration+@EnableAutoConfiguration+@ComponentScan,其中掃描包的范圍為啟動類所在包和子包,不包括第三方的jar包。如果我們需要掃描通過maven依賴添加的jar,我們就要單獨使用@ComponentScan注解掃描第三方包。
但是,如果@SpringBootApplication和@ComponentScan注解共存,那么@SpringBootApplication注解的掃描的作用將會失效,也就是說不能夠掃描啟動類所在包以及子包了。因此,我們必須在@ComponentScan注解配置本工程需要掃描的包范圍。
結果還是沒能解決,最后拿另一個項目對比着檢查,才發現是pom.xml中的依賴,我導的是mybatis,而正確的依賴應該是導入mybatis-spring-boot-starter這個依賴(難受,@Mapper這個注解引入的都是import org.apache.ibatis.annotations.Mapper;)