一 点睛
Spring Boot对Spring Data JPA的自动配置放置在如下路径:
二 源码分析
1 JpaRepositoriesAutoConfiguration类分析
@Configuration
@ConditionalOnBean(DataSource.class)
@ConditionalOnClass(JpaRepository.class)
@ConditionalOnMissingBean({ JpaRepositoryFactoryBean.class,
JpaRepositoryConfigExtension.class })
@ConditionalOnProperty(prefix = "spring.data.jpa.repositories", name = "enabled", havingValue = "true", matchIfMissing = true)
@Import(JpaRepositoriesAutoConfigureRegistrar.class)
//JpaRepositoriesAutoConfiguration依赖于HibernateJpaAutoConfiguration配置
@AutoConfigureAfter(HibernateJpaAutoConfiguration.class)
public class JpaRepositoriesAutoConfiguration {
}
2 JpaRepositoriesAutoConfigureRegistrar类分析
class JpaRepositoriesAutoConfigureRegistrar
extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class extends Annotation> getAnnotation() {
return EnableJpaRepositories.class;
}
@Override
protected Class> getConfiguration() {
return EnableJpaRepositoriesConfiguration.class;
}
@Override
protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() {
return new JpaRepositoryConfigExtension();
}
//自动开启了Spring Data JPA的支持,所以无需在配置类中显示声明@EnableJpaRepositories
@EnableJpaRepositories
private static class EnableJpaRepositoriesConfiguration {
}
}
三 Spring下使用Spring Data JPA
在Spring Boot下使用Spring Data JPA,在项目的Maven依赖里添加spring-boot-starter-data-jpa,然后只需定义DataSource、实体类和数据访问层,并在需要使用数据访问的地方注入数据访问层的Bean即可,无需任何额外配置。