springboot 啓動報錯Field XXX required a bean of type XXX that could not be found.

今天自己搭建springboot項目,連接數據庫,啓動的時候發現報錯,如下:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-08 14:28:58.065 ERROR 4656 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userTextMapper in com.springboot.demo.service.UserTextService required a bean of type 'com.springboot.demo.dao.UserTextMapper' that could not be found.


Action:

Consider defining a bean of type 'com.springboot.demo.dao.UserTextMapper' in your configuration.

Disconnected from the target VM, address: '127.0.0.1:56232', transport: 'socket'

Process finished with exit code 1

然後各種百度,對這種錯誤的解決方法做了以下總結:

1.包結構的問題。

項目啓動時,只有@SpringBootApplication 所在的包被掃描,在本例中,啓動類是MainApplication.java, 也就是MainApplication.java類所在的這個包,而其他的controller和service以及mapper在其他的包裏,所以並沒有被掃描。解決方法是,把啓動類放在外層包。如下:


2.沒有自動注入導致。

你的service類上面沒有@service註解或者mapper上沒有@Repository註解,但是這種情況比較少見,一般不會忘記。



3.配置了mybatis,但沒有指定掃描的包。

方法1:啓動類加註釋:@MapperScan(basePackages = { "mapper所在的包路徑" }, sqlSessionFactoryRef = "sqlSessionFactory"),表示掃描xx.xx.mapper包下的所有mapper。 


方法2:直接在你生成出來的xxxMapper.java類上加@Mapper標籤。

以上。希望後期在遇到類似問題,知道如何解決。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章