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标签。

以上。希望后期在遇到类似问题,知道如何解决。

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