gpt4 book ai didi

java - 为什么我不使用 FileSystemResource 类读取 xml 文件

转载 作者:行者123 更新时间:2023-11-30 02:35:42 24 4
gpt4 key购买 nike

问题:

我创建了一个程序,它将使用 FilesystemResource 从指定路径读取 applicationContext.xml 文件并调用 B.Method。我无法理解为什么我会收到这样的错误:

Can anyone guide me how to solve this problem:

下面是代码

public static void main(String[] args) {
Resource res=null;
BeanFactory factory=null;
Object obj=null;
WishMessageGenerator generator=null;
//Locate Cfg File
res=new FileSystemResource("com/jc/cfgs/applicationContext.xml");
//Create IOC Container
factory=new XmlBeanFactory(res);
//getBean Class Object
obj=factory.getBean("wish");
//TypeCasting
generator=(WishMessageGenerator)obj;
//Invoke Businees Method
System.out.println("Message ="+generator.wishMsg("jalaj"));

}

}

显示错误:

Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [/Users/mansi/Desktop/springapp/SpringApp4/com/jc/cfgs/applicationContext.xml]; nested exception is java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:79)
at org.springframework.beans.factory.xml.XmlBeanFactory.<init>(XmlBeanFactory.java:67)
at com.jc.test.Test.main(Test.java:20)
Caused by: java.io.FileNotFoundException: com/jc/cfgs/applicationContext.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at org.springframework.core.io.FileSystemResource.getInputStream(FileSystemResource.java:115)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
... 4 more

DirectoryStructure

最佳答案

如果资源位于类路径中,则不应使用旨在指定绝对路径的 FileSystemResource

ClassPathResource也是一个org.springframework.core.io.Resource实现更合适。

在您的实际代码中,src 文件夹位于类路径中,因此这应该没问题:

res = new ClassPathResource("com/jc/cfgs/applicationContext.xml");

关于java - 为什么我不使用 FileSystemResource 类读取 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43166322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com