Springboot应用中@EntityScan和@EnableJpaRepositories的使用详解
在Springboot应用开发中使用JPA时,通常在主应用程序所在包或者其子包的某个位置定义我们的Entity和Repository,这样基于Springboot的自动配置,无需额外配置,我们定义的Entity和Repository即可被发现和使用。但有时候我们需要定义Entity和Repository不在应用程序所在包及其子包,那么这时候就需要使用@EntityScan和@EnableJpaRepositories了。
上面提到的Entity和Repository指的是通过类似下面的方式定义的Entity和Repository :
@Entity
@Table(name = "grade")
public class Grade {
// 省略具体内容
}
@Repository
public interface GradeRepository extends JpaRepository<Grade, Long>, JpaSpecificationExecutor<Grade> {
// 省略具体内容
}
@EntityScan
@EntityScan用来扫描和发现指定包及其子包中的Entity定义。其用法如下:
@EntityScan(basePackages = {"com.department.entities","come.employee.entities"})
如果多处使用@EntityScan,它们的basePackages集合能覆盖所有被Repository使用的Entity即可,集合有交集也没有关系。
但是如果不能覆盖被Repository使用的Entity,应用程序启动是会出错,比如:
Not a managed type: com.customer.entities.Customer
@EnableJpaRepositories
@EnableJpaRepositories用来扫描和发现指定包及其子包中的Repository定义。
其用法如下:
@EnableJpaRepositories(basePackages = {"com.department.repositories","come.employee.repositories"})
如果多处使用@EnableJpaRepositories,它们的basePackages集合不能有交集,并且要能覆盖所有需要的Repository定义。
如果有交集,相应的Repository会被尝试反复注册,从而遇到如下错误:
The bean ‘OrderRepository’, defined in xxx, could not be registered. A bean with that name has already been defined in xxx and overriding is disabled.
如果不能覆盖所有需要的Repository定义,会遇到启动错误:
Parameter 0 of method setCustomerRepository in com.service.CustomerService required a bean of type ‘come.repo.OrderRepository’ that could not be found.
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
gateway与spring-boot-starter-web冲突问题的解决
这篇文章主要介绍了gateway与spring-boot-starter-web冲突问题的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
详解@ConditionalOnMissingBean注解的作用
这篇文章主要介绍了详解@ConditionalOnMissingBean注解的作用,@ConditionalOnMissingBean,它是修饰bean的一个注解,主要实现的是,当你的bean被注册之后,如果而注册相同类型的bean,就不会成功,它会保证你的bean只有一个,需要的朋友可以参考下2023-10-10
Spring Boot整合elasticsearch的详细步骤
这篇文章主要介绍了Spring Boot整合elasticsearch的详细步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2019-04-04


最新评论