IntelliJ IDEA中Spring-Context依赖解析失败及注解报错求助
问题描述
在学习Spring并按书籍示例实践时,遇到以下问题:
- pom.xml中引入
spring-context依赖后,版本标签标红提示“dependency not found” - 代码里的
@Configuration、@Bean、AnnotationConfigApplicationContext(注:代码中拼写错误,应为Annotation而非Annotaion)均无法解析 - 尝试更换6.0.3等版本,问题仍未解决
pom.xml内容:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>SpringLearning</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.6.RELEASE</version> <!-- this is RED highlighted "dependency not found" --> </dependency> </dependencies> </project>
相关配置类代码:
@Configuration public class MyConfig { @Bean public Parrot parrot() { var p = new Parrot(); p.setName("abc"); return p; } }
主类代码:
public class Main { public static void main(String[] args) { // 注:类名拼写错误,正确应为AnnotationConfigApplicationContext var context = new AnnotaionConfigApplicationContext(); Parrot p = new Parrot(); } }
Parrot实体类代码:
public class Parrot { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
解决方法
1. 修正JDK与Spring版本兼容性
- 若使用Spring 6.x版本(如6.0.3),必须搭配JDK 17及以上版本,需修改pom.xml的JDK配置:
<properties> <maven.compiler.source>17</maven.compiler.source> <maven.compiler.target>17</maven.compiler.target> </properties> - 若继续使用JDK 11,建议保留Spring 5.x版本(如原5.2.6.RELEASE),该版本对JDK 11完全兼容。
2. 配置国内Maven镜像
Maven默认中央仓库访问可能受限,添加阿里云镜像加速依赖下载:
- 找到Maven的
settings.xml文件(路径:~/.m2/settings.xml或Maven安装目录下的conf/settings.xml) - 在
<mirrors>标签内添加:<mirror> <id>aliyunmaven</id> <mirrorOf>central</mirrorOf> <url>https://maven.aliyun.com/repository/public</url> </mirror>
3. 强制更新Maven依赖
- IDE操作:右键项目 → Maven → Clean,再执行Maven → Install(或Reload All Maven Projects)
- 命令行执行:
mvn clean install -U-U参数会强制Maven更新远程仓库索引和依赖缓存,解决本地缓存过期问题。
4. 验证IDE的Maven配置
- IDEA:File → Settings → Build, Execution, Deployment → Build Tools → Maven,检查
Maven home directory指向正确的Maven安装路径,User settings file指向配置好镜像的settings.xml - Eclipse:Window → Preferences → Maven → Installations,选择正确的Maven安装;再进入Maven → User Settings,指定
settings.xml路径
5. 手动修复依赖(极端情况)
若以上步骤无效,可手动下载依赖到本地仓库:
- 找到对应版本的
spring-contextjar包 - 将jar包放入本地仓库路径:
~/.m2/repository/org/springframework/spring-context/[对应版本号]/ - 重启IDE并重新加载Maven项目
另外,主类中AnnotaionConfigApplicationContext存在拼写错误,修正为AnnotationConfigApplicationContext后才能正常使用。
内容的提问来源于stack exchange,提问作者Ajay Patidar
相关产品推荐
相关产品推荐

