application-Context.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

    <bean id="student" class="com.lyx.domain.Student">
        <property name="stuno" value="1"/>
        <property name="stuname" value="Gavin"/>
        <property name="stuage" value="22"/>
    </bean>

</beans>

测试运行报错 

 代码如下:

package Test;

import com.lyx.domain.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class test {
    public static void main(String[] args) {
//        Student student = new Student();
//        student.setStuno(1);
//        student.setStuname("Gavin");
//        student.setStuage(22);
        //Spring上下文对象
        //ClassPathXmlApplicationContext:从类路径中的XML文件加载上下文中定义的信息,把上下文定义的文件当成类路径资源。
        ApplicationContext context = new ClassPathXmlApplicationContext("application-Context.xml");
        //FileSystemXmlApplicationContext:从文件系统中的XML文件加载上下文中定义的信息。
//        FileSystemXmlApplicationContext context1 = new FileSystemXmlApplicationContext("src/main/resources/application-Context.xml");
        Student student1 = (Student) context.getBean("student");
        System.out.println(student1);
    }
}

原因: 

applicationcontext放置的位置不同也会用到不同的解析方式去读取他的位置
ApplicationContext接口的常用实现类有以下3个。
•  FileSystemXmlApplicationContext:从文件系统中的XML文件加载上下文中定义的信息。
•  ClassPathXmlApplicationContext:从类路径中的XML文件加载上下文中定义的信息,把上下文定义的文件当成类路径资源。
•  XmlWebApplicationContext:从Web系统中的XML文件加载上下文中定义的信息。

再看我application-Context.xml文件路径

解决如下:运行成功!

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐