如何解决spring中从xml文件中获取bean时出错
我是春天的新手。我创建了 config.xml
,我在其中创建了 bean。当我尝试使用 getBean
时,出现以下错误:
IOException 从类路径资源解析 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 可用
我的主函数存在于 src/main/java/org/example/App.java
我的 config.xml 存在于 src/main/java/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 文件 public class Shell {
String materialSMYS,outerDiameter,materialThickness,jointFactor,pressure,corrosionAllowance;
double designPressureD,corrosionAllowanceD,allowableStressD,materialDiameterD,materialThicknessD,jointFactorD,result;
public Shell(String materialSMYS,String outerDiameter,String materialThickness,String jointFactor,String pressure,String corrosionAllowance){
this.materialSMYS = materialSMYS;
this.outerDiameter = outerDiameter;
this.materialThickness = materialThickness;
this.jointFactor = jointFactor;
this.pressure = pressure;
this.corrosionAllowance = corrosionAllowance;
}
public double thickness(){
designPressureD = Double.parseDouble(pressure);
corrosionAllowanceD = Double.parseDouble(corrosionAllowance);
allowableStressD = Double.parseDouble(materialSMYS);
materialDiameterD = Double.parseDouble(outerDiameter);
materialThicknessD = Double.parseDouble(materialThickness);
jointFactorD = Double.parseDouble(jointFactor);
result = this.designPressureD*this.materialDiameterD/ (this.allowableStressD*this.jointFactorD - 0.6*designPressureD);
return result;
放入 src/main/resources(默认情况下,maven 会将您的 Java 源文件放入 config.xml
,并将您的资源文件放入 { {1}})
创建 src/main/java
对象时不需要 src/main/resources
关键字,只需使用 classpath
如下:
ClassPathXmlApplicationContext
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。