Spring应用迁移至Spring Boot时出现Hibernate初始化entityManagerFactory创建错误
错误详情
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'entityManagerFactory' threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/orm/hibernate5/SpringBeanContainer org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.entityManagerFactory(JpaBaseConfiguration.java:132) ~[spring-boot-autoconfigure-2.5.1.jar:2.5.1] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_271] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_271] Caused by: java.lang.ClassNotFoundException: org.springframework.orm.hibernate5.SpringBeanContainer at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
报错截图

根因说明
报错核心是Spring Boot版本与依赖的Spring ORM、Hibernate版本不兼容:你使用的Spring Boot 2.5.1要求配套Spring ORM版本不低于5.3.x,只有该版本才包含
org.springframework.orm.hibernate5.SpringBeanContainer类,项目中要么缺失对应版本的spring-orm包,要么存在多版本spring-orm冲突,要么手动指定的Hibernate版本和当前Spring Boot版本不匹配。
定位步骤
- 执行依赖冲突检查:Maven项目执行
mvn dependency:tree | grep spring-orm,Gradle项目执行gradle dependencies | grep spring-orm,确认当前引入的spring-orm版本是否低于5.3.x,是否存在多个版本并存的情况。 - 检查是否手动指定了Hibernate版本,未使用Spring Boot官方的依赖管理规则。
解决方案
- 优先复用Spring Boot官方依赖管理:Maven项目确保父pom继承
spring-boot-starter-parent,引入spring-boot-starter-data-jpa时不手动指定版本号,starter会自动引入匹配当前Spring Boot版本的所有相关依赖。 - 如需手动指定Hibernate版本,确保版本适配:Spring Boot 2.5.x仅支持Hibernate 5.4.x、5.5.x版本,禁止使用Hibernate 6.x或低于5.4的版本。
- 排除冲突的低版本spring-orm依赖:如果依赖树中发现第三方包引入了低于5.3.x的spring-orm,在该依赖的声明中添加exclusion规则排除低版本spring-orm。
- 清理缓存后重新构建:执行
mvn clean install或gradle clean build,避免本地缓存的旧依赖影响构建结果。
内容的提问来源于stack exchange,提问作者ankit giri
相关产品推荐
相关产品推荐

