首页 > 解决方案 > 即使添加了 Maven 依赖项,也无法识别 ApplicationContext

问题描述

我开始了一门关于 Spring Boot 的课程,并且正在进行依赖注入。我遇到了一个ApplicationContext似乎无法解决 的问题: 问题截图

如您在 pom 文件中所见,我添加了 maven 依赖项: pom file screenshot

但它仍然无法识别ApplicationContext,我无法在任何地方找到解决方案。

编辑:整个 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.6</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <groupId>com.example</groupId>
  <artifactId>DependencyInjectionDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>DependencyInjectionDemo</name>
  <description>Demo project for Spring Boot</description>
  <properties>
    <java.version>11</java.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.12</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

标签: spring-bootintellij-ideaclasspathmaven-dependency

解决方案


您不需要显式添加spring-context依赖项,因为它是spring-boot-starter. 除此之外,这对我来说似乎很好,但我们可以做三件事:

  1. 检查您实际上是在导入org.springframework.context.ApplicationContext而不是在导入其他类;
  2. 强制重新加载 IntelliJ 中的所有依赖项(右键单击您的项目 --> Maven --> 重新加载项目);
  3. 清除您的.m2文件夹(或至少org/springframework其中的子路径文件夹)。那里可能有一些损坏的 JAR。

推荐阅读