SpringBoot 整合JPA 出現 Error creating bean with name 'userRepository':Not a managed type 問題分析和解決方案

日誌信息:

  1. Caused by:
  2. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed;
  3. nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.heima.domain.User

bean注入失敗,簡單來說就是在加載SpringBoot 的啓動類時JPA的實體類找不到,沒有被掃描到。導致這樣的情況有以下幾種可能。

 1、實體類上缺少@Entity註解---在實體類上加上註解即可

  1. @Entity
  2. public class User {
  3. // 主鍵
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.IDENTITY)
  6. private Long id;

 2、 沒有按照SpringBoot的約定,默認掃描(SpringBootApplication.java 啓動類相對的兄弟包及其子包)

 解決方案

 2.1  將SpringBootApplication.java(啓動類)放置到更高層級的包,使得項目結構符合SpringBoot約定掃描的規則

 2.2  在啓動類中添加要掃描的包

          2.2.1        @ComponentScan(basePackages = "com.boot.demo.xxx.*.*")

                          用於掃描@Controller @Service

          2.2.2        @EnableJpaRepositories(basePackages = "com.boot.demo.xxx.*.dao") 

                          用於掃描Dao @Repository

         2.2.3        @EntityScan("com.boot.demo.xxx.*.*")

                           用於掃描JPA實體類 @Entity

  1. @SpringBootApplication
  2. @EntityScan("com.heima.domain")
  3. public class SpringbootJpaApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(SpringbootJpaApplication.class, args);
  6. }
  7. }

 

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