【问题标题】:Load resource from classpath in inside jar从内部 jar 中的类路径加载资源
【发布时间】:2020-09-02 08:49:51
【问题描述】:

我正在尝试将资源 csv 文件传递​​到使用我的 Sprint Boot 应用程序的 jar 内部。 我总是得到一个文件不存在的响应,尽管方法 get = ReactiveWebContext resource [src/main/resources/file.csv] 的 Resource 参数

  • 在我的项目中,我的文件位于 src/main/resources/file.csv
  • 在 application.properties 中,我定义:

    file.csv.path=classpath*:file.csv
    
  • 在配置类中:

    @Configuration
    @PropertySources({
    @PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = 
     true)
    })
    public class BookConfiguration {
    }
    
  • 在内部 jar 中:Config 类:

    @Configuration
    @Import({BoleroConfiguration.class})
    public class BoleroTestingInfraConfiguration {
    
    @Bean
    @ConditionalOnMissingBean
    public FileProvider fileProvider(@Value("${file.csv.path}") Resource fileResource) throws 
    IOException {
        return new TestingProvider(fileResource);
    }
    
  • TestingProvider.class

    public class TestingProvider {
    
     private final Map<String, Set<Book>> idToBook;
    
     public TestingProvider(Resource fileResource) throws IOException {
       idToBook = getBooks(fileResource);
     }
    
     public Map<String, Set<Book>> getBooks(Resource fileResource) {
        if (fileResource == null || !fileResource.exists() ||
            !fileResource.getFile().exists() || !fileResource.getFile().isFile()) {
        return Optional.empty();
        }
    
     ....
     }
    }
    

感谢您的帮助

【问题讨论】:

    标签: java spring-boot file-io jar resources


    【解决方案1】:

    1) 您指定的路径不正确。应该不是classpath*:file.csv,而是classpath:file.csv

    2) 通常在 JAR 中不会有 src/main/resources/file.csvsrc/main/resources/file.csv 文件只存在于源代码中。路径 src/main/resources 对应于 JAR 的 root 级别。因此文件 file.csv 将位于 JAR 的 root 级别。

    【讨论】:

    • 已修复。还是没有找到资源文件。
    • 解释如何构建 JAR。使用 Gradle?与马文?在您创建 JAR 的位置显示相应的配置。
    • 我用maven构建了jar。
    • 变量到file.path的快捷方式解决了这个问题。你知道为什么吗?有限制吗?
    • 不行,变量名不能影响它。如果它有效,则意味着您的代码中还有一些您没有显示的内容。
    猜你喜欢
    • 2010-12-26
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2011-04-22
    • 2010-10-26
    • 1970-01-01
    相关资源
    最近更新 更多