- Caused by:
- org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed;
- nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.heima.domain.User
bean注入失敗,簡單來說就是在加載SpringBoot 的啓動類時JPA的實體類找不到,沒有被掃描到。導致這樣的情況有以下幾種可能。
1、實體類上缺少@Entity註解---在實體類上加上註解即可
-
- @Entity
- public class User {
- // 主鍵
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- 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
- @SpringBootApplication
- @EntityScan("com.heima.domain")
- public class SpringbootJpaApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringbootJpaApplication.class, args);
- }
- }