【问题标题】:Spring Boot Unable to find File using ClassPathResourceSpring Boot无法使用ClassPathResource找到文件
【发布时间】:2017-09-12 00:56:43
【问题描述】:

使用 Spring Boot。我正在尝试使用 Apache POI 库解析项目中本地存储的 excel 文件。我的目录结构是这样的:

  • src

    • 主要

      • java

        • com.app
          • 控制器
          • 型号
          • 存储库
      • 资源

        • 静态
          • Test.xlsx

File excel = new ClassPathResource("Test.xlsx").getFile();

File file = new File(classLoader.getResource("src/main/resources/static/test.xlsx").getFile());

我已经尝试了上述两种访问文件的方法,并且我尝试了文件路径的许多变体,但没有任何效果。我没有收到构建错误或运行时错误,根本找不到该文件,当我尝试调用该方法时,我在该行上得到 NullPointerException。

【问题讨论】:

  • 假设post 可能会为您提供解决方案。
  • @RajithPemabandu 我已经尝试过该帖子中提出的解决方案,但仍未找到

标签: java spring-boot


【解决方案1】:

假设你只是重写了扩展 WebMvcConfigurerAdapter@Configuration 类的 addResourceHandlers 方法

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

这是一篇关于 Spring 资源的博文 - here

查看 springdocumentation 了解更多详情。

【讨论】:

  • 我没有使用 Spring MVC 我只是有简单的设置。是否也可以通过在 application.properties 中添加“spring.mvc.static-path-pattern=/resources/**”来实现?
【解决方案2】:

我相信你的情况是正确的

new ClassPathResource("/static/Test.xlsx").getFile()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 2017-06-06
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多