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也無法配置,明天繼續吧。

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