SpringBoot統合JPAにError creating bean with name'userRepository':Not a managed type問題の分析と解決策が現れた

1474 ワード

ログ情報:

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);
	}
}