首页 > 解决方案 > spring 从 xml 文件中获取 bean 时出错

问题描述

我是春天的新手。我config.xml在其中创建了 bean。当我尝试使用getBean时,我收到以下错误:

IOException 从类路径资源 [config.xml] 解析 XML 文档;嵌套异常是 java.io.FileNotFoundException:类路径资源 [config.xml] 无法打开,因为它不存在。

我之前使用过这条线。

ApplicationContext context= new ClassPathXmlApplicationContext(" config.xml");

Student Student1=(Student) context.getBean("s1");

然后,我将代码更改为:

ApplicationContext context= new ClassPathXmlApplicationContext("classpath*: config.xml");

但是,现在我得到了新的错误: 没有名为 's1' 的 bean 可用

我的主要功能存在于src/main/java/org/example/App.java

我的 config.xml 存在于src/main/java/config.xml

内容config.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">

<bean id="s1" class="org.example.Student"> <!--org.example is groupId-->
    <property name="studentId">
        <value>22344</value>
    </property>
    <property name="studentName">
        <value>AP</value>
    </property>
    <property name="studentAddress">
        <value>L</value>
    </property>
</bean>

标签: javaandroidspringjavabeans

解决方案


您必须将 xml 文件config.xml放入src/main/resources(默认情况下,maven 会在其中查找 Java 源文件src/main/java并将您的资源文件放入src/main/resources

classpath创建ClassPathXmlApplicationContext对象时不需要关键字,只需使用ClassPathXmlApplicationContext("config.xml")如下:

ApplicationContext context= new ClassPathXmlApplicationContext("config.xml");
Student student1=(Student) context.getBean("s1");
System.out.println(student1.getStudentId());

推荐阅读