从jar中的类路径加载资源

时间:2020-05-16 13:39:25

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

我正在尝试将资源csv文件传递到jar中,我的Sprint Boot应用程序已使用。 尽管方法获得的Resource参数= ReactiveWebContext资源[src / main / resources / file.csv]

,但我始终会收到文件不存在的响应
  • 在我的项目中,我的文件位于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();
        }
    
     ....
     }
    }
    

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

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

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