Spring新手遇ClassPathXmlApplicationContext无法解析为类型问题求助
解决ClassPathXmlApplicationContext无法解析的编译错误
问题详情
编译错误提示:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
ClassPathXmlApplicationContext cannot be resolved to a type
ClassPathXmlApplicationContext cannot be resolved to a typeat springintro.Main.main(Main.java:13)
相关配置文件与代码如下:
Spring配置文件(applicationCustomer.xml)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <bean id="database" class="springintro.CustomerDal"> </bean> </beans>
Java代码(Main.java)
package springintro; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationCustomer.xml"); CustomerManager manager = new CustomerManager(context.getBean("database",ICustomerDal.class)); manager.add(); } //IoC - Inversion of Control //Dependency Injection //Spagetti Code //SOLID }
解决方案
确认Spring Context依赖已引入
ClassPathXmlApplicationContext属于spring-context模块,必须确保项目中包含该依赖:- Maven项目,在
pom.xml中添加:<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> <!-- 替换为你使用的Spring版本 --> </dependency> - Gradle项目,在
build.gradle中添加:implementation 'org.springframework:spring-context:5.3.20' // 替换为对应版本
- Maven项目,在
刷新项目依赖
在STS4中:- Maven项目:右键项目 → Maven → Update Project
- Gradle项目:右键项目 → Gradle → Refresh Gradle Project
验证导入语句正确性
确认Main类中的导入语句为import org.springframework.context.support.ClassPathXmlApplicationContext;,无拼写或路径错误。清理并重新编译项目
点击菜单栏Project → Clean...,选择目标项目清理后重新编译,清除编译缓存问题。
内容的提问来源于stack exchange,提问作者Jolika
相关产品推荐
相关产品推荐

