java—在spring中从xml文件获取bean时出错

2ekbmq32  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(340)

我刚到Spring。我创造了 config.xml 我创造了豆子。当我尝试使用 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>
ejk8hzay

ejk8hzay1#

必须将xml文件 config.xml into 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());

相关问题