Spring JPA测试抛出java.lang.IllegalStateException问题求助
这个异常的核心原因是Spring Test和Spring Core版本不兼容,我们一步步拆解问题并解决:
1. 为什么会出现NoSuchMethodError?
你使用了Spring Test 4.3,但搭配的是Spring Core 4.1.4。org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations()这个方法是Spring Core 4.3版本才新增的API,旧版4.1.4里根本没有这个方法,所以Spring Test启动时找不到它,直接抛出异常。
2. 解决版本兼容问题
你有两个可选方案:
方案A:统一升级所有Spring依赖到4.3.x稳定版
把Spring Core、Spring Test、Spring Context等所有相关依赖的版本都改成同一个4.3.x版本(比如4.3.30.RELEASE,这是4.3分支的最后一个稳定版,Maven仓库肯定有)。这样所有组件API完全兼容,不会再出现方法缺失的问题。
举个Maven依赖的例子:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.30.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.30.RELEASE</version> <scope>test</scope> </dependency> <!-- 其他Spring依赖(spring-context、spring-web等)也统一用这个版本 -->
方案B:降级Spring Test到和Core匹配的4.1.x版本
如果你的项目不能升级Spring Core版本,那就把Spring Test降级到4.1.x系列(比如4.1.9.RELEASE,这个版本在Maven中央仓库是存在的,不会出现.zip文件错误)。确保Spring Test版本和Core版本完全一致,API就能匹配上。
Maven依赖示例:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.9.RELEASE</version> <scope>test</scope> </dependency>
3. 额外检查:配置文件路径是否正确
你当前的@ContextConfiguration路径是classpath:/webapp/WEB-INF/dispatcher-servlet.xml,但在标准Maven项目结构里,src/main/webapp目录不在classpath范围内(默认classpath是src/main/resources、src/main/java等)。所以这个路径大概率找不到配置文件,会引发后续问题。
你可以做两种调整:
- 把
dispatcher-servlet.xml复制到src/main/resources目录下,然后路径改成classpath:dispatcher-servlet.xml - 或者用文件系统路径指定:
@ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/dispatcher-servlet.xml"})
最后验证
修改完版本和路径后,重新执行mvn clean install,再运行测试类,应该就能正常启动Spring上下文并执行测试了。
内容的提问来源于stack exchange,提问作者Saminda Peramuna

