spring boot: 构建项目时报错Not a managed type

今天在学习使用Spring Data JPA的时候,将bean和JpaRepository放在了不同的package中,导致无法构建项目,报以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'readingListRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class bean.Book

异常是逐层抛出的,所以要定位到错误的地方,应该看最底下的内容,

java.lang.IllegalArgumentException: Not a managed type: class bean.Book

也就是我们没有按照SpringBoot的约定,默认扫描(application.java 入口类相对的兄弟包及其子包)
解决方法1:将bean和JpaRepository放在同一个package中。
解决方法2:在JpaRepository上添加注释,使得它能找到bean

@EntityScan("bean.Book")

这里整合以下常见的配置

@ComponentScan(basePackages = "com.boot.demo.xxx.*.*")
用于扫描@Controller @Service


 @EnableJpaRepositories(basePackages = "com.boot.demo.xxx.*.dao") 
用于扫描Dao @Repository


@EntityScan("com.boot.demo.xxx.*.*")
用于扫描JPA实体类 @Entity

好吧,现在完全不知道spring-boot的文件结构要如何,多创建了几个包,现在各种找不到类,controller也无法配置,明天继续吧。

上一篇:连接mysql报错Table ‘performance_schema.session_variables’


下一篇:mac下启动/停止/重启mysql服务