繁体   English   中英

从 spring 中的 xml 文件中获取 bean 时出错

[英]Error in fetching beans from xml file in spring

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

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

我之前使用过这条线。

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

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

然后,我将代码更改为:

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

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

我的主要 function 存在于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>

You must put the xml file config.xml into src/main/resources (by default maven look for you Java source files into src/main/java and for your resource files into src/main/resources )

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM