java - 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>
解决方案
您必须将 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());
推荐阅读
- azure-pipelines - Azure Pipelines API - 获取构建代理信息
- lua - NSE:未能初始化脚本引擎:
- python - 如何在按住键的同时刷新 OpenCV 窗口
- sql-server - 尽管修复了防火墙设置,但 Azure 服务器访问问题
- reactjs - Reselect:如何缓存写入reducer的数据?
- jenkins-pipeline - 根据作业执行某些阶段
- reactjs - .ts 和 .tsx 扩展名有什么区别。两者都用作响应中打字稿文件的扩展。那么我们应该在哪里使用它们呢?
- c# - 是否可以将 select 作为表达式传递以进行投影 DbSet?
- objective-c - 如何在 Objective C 或 Swift 中使用重复线性渐变
- azure - 仅部分用户出现“权限不足,无法完成操作”错误