Spring 4.3.3升级至5.0.1遇依赖异常,求技术支持
刚从Spring 4.x升级到5.x踩过类似的依赖注入坑,结合你提供的异常信息(UnsatisfiedDependencyException最终指向notifyRepository的BeanCreationException),给你几个针对性的排查方向:
先抓完整的异常栈信息
你贴的异常只到BeanCreationException就结束了,这个异常的嵌套细节才是根因——比如是Hibernate类找不到、Spring Data JPA方法不兼容,还是Security配置冲突。一定要把控制台输出的完整异常堆栈贴出来,比如:SEVERE: Exception sending context initialized event...
org.springframework.beans.factory.UnsatisfiedDependencyException: ...
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'notifyRepository': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/jpa/HibernatePersistenceProvider这种完整信息才能直接定位问题。
同步Spring Security版本到5.0.x
Spring 5.0.x和Spring Security 4.x存在API不兼容(比如SecurityContextHolder的内部实现、依赖注入逻辑),如果你的项目里Spring Security还是4.x版本,必须升级到5.0.1(和Spring核心版本完全一致)。比如Maven依赖:<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.0.1.RELEASE</version> </dependency>检查JPA/Spring Data相关依赖版本
Spring 5.0.x对JPA的最低版本要求是Hibernate 5.0+,Spring Data JPA需要对应Kay版本(Spring Data Kay SR1对应Spring 5.0.1)。如果之前用的是Hibernate 4.x,必须升级到5.0+,比如:<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.11.1.RELEASE</version> <!-- Kay SR1 --> </dependency>版本不匹配是升级后Repository创建失败的最常见原因。
排查字段注入的注解兼容性
虽然Spring 5依然支持@Autowired字段注入,但如果你的代码里混用了@Resource或者Spring 4专属的注入注解,可能出现兼容性问题。可以临时把字段注入改成构造器注入试试——Spring 5推荐构造器注入,而且能避免很多初始化顺序问题:// 原来的字段注入 @Service public class SignUpServiceImpl { @Autowired private NotifyRepository notifyRepository; } // 改成构造器注入 @Service public class SignUpServiceImpl { private final NotifyRepository notifyRepository; public SignUpServiceImpl(NotifyRepository notifyRepository) { this.notifyRepository = notifyRepository; } }检查Spring上下文的初始化顺序
如果你的Spring Security配置类和Repository配置类加载顺序有问题,可能导致Service依赖Repository时,Repository还没初始化。可以试试把Repository所在的配置类加上@Priority(0),确保它先被加载,或者在Service类上用@DependsOn("notifyRepository")强制指定依赖顺序(这是临时 workaround,最好找到顺序冲突的根因)。
我之前升级时就是因为Spring Security版本没同步到5.x,导致Repository的Bean创建失败,同步版本后问题直接解决。如果上面的方法还不行,一定要把完整的异常栈发出来,这样能更精准定位!
内容的提问来源于stack exchange,提问作者Kesavulu R

