【问题标题】:Unable to locate xml file using ClassPathResource in Spring Java configuration无法在 Spring Java 配置中使用 ClassPathResource 定位 xml 文件
【发布时间】:2019-10-01 12:54:48
【问题描述】:

我正在将项目从基于 xml 的配置迁移到基于 java 的配置。

我能够成功定义除一个之外的所有 bean。 XMLViewResolver 我们使用的是 JasperReports,所以所有的 jrxml 文件都在 reports.xml 中定义 从我的类路径中,我无法找到 xml 文件。

我只尝试在 ClassPathResource 中添加 reports.xml,但仍然在项目构建期间出现错误。

@Bean 
public ViewResolver xmlViewResolver() {
        logger.info("xmlViewResolver");
        XmlViewResolver bean = new XmlViewResolver();
        bean.setOrder(10);
        bean.setLocation(new ClassPathResource("WEB-INF/spring/appServlet/reports.xml"));
        return bean;
    }
Caused by: java.io.FileNotFoundException: class path resource [WEB-INF/spring/appServlet/reports.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330)
    ... 47 more

旧xml代码:

<beans:bean id="viewResolver"
        class="org.springframework.web.servlet.view.XmlViewResolver">
        <beans:property name="order" value="0" />
        <beans:property name="location"
            value="/WEB-INF/spring/appServlet/reports.xml" />
</beans:bean>

【问题讨论】:

  • 它不在 class 路径(.class 文件也在其中),而是网站上 WEB_INF 目录中的实际文件。
  • 将reports.xml 放在src/main/resources 下的某处,并将那里的路径用作类路径资源
  • @JoopEggen,感谢您的回复。即使使用“spring/appServlet/reports.xml”,它也会显示相同的错误原因:java.io.FileNotFoundException:类路径资源 [spring/appServlet/reports.xml]
  • 谢谢。一旦我将reports.xml 移动到src/main/resources 并将位置更改为bean.setLocation(new ClassPathResource("reports.xml"));,它现在就可以工作了。

标签: java spring classpath filenotfoundexception


【解决方案1】:

我不得不将 reports.xml 移动到 src/main/resources 并更改位置如下

        bean.setLocation(new ClassPathResource("reports.xml"));

现在项目能够读取和检测 .xml 文件

【讨论】:

    猜你喜欢
    • 2017-09-12
    • 2015-12-12
    • 2014-05-21
    • 2016-08-10
    • 1970-01-01
    • 2014-02-09
    • 2013-10-24
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多