简体   繁体   English

从 jar 中的类路径加载资源

[英]Load resource from classpath in inside jar

I am trying to pass a resource csv file to inside jar my Sprint Boot application is used.我正在尝试将资源 csv 文件传递到 jar 内部,我使用了 Sprint Boot 应用程序。 I alway get a response that the file is not exist although the Resource parameter that the method get = ReactiveWebContext resource [src/main/resources/file.csv]尽管方法获取的 Resource 参数 = ReactiveWebContext 资源 [src/main/resources/file.csv],但我总是收到该文件不存在的响应

  • In my project, I have the file located in src/main/resources/file.csv在我的项目中,我的文件位于 src/main/resources/file.csv
  • In application.properties, I define:在 application.properties 中,我定义:

     file.csv.path=classpath*:file.csv
  • In the config class:在配置 class 中:

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

     @Configuration @Import({BoleroConfiguration.class}) public class BoleroTestingInfraConfiguration { @Bean @ConditionalOnMissingBean public FileProvider fileProvider(@Value("${file.csv.path}") Resource fileResource) throws IOException { return new TestingProvider(fileResource); }
  • The TestingProvider.class测试提供者.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(). }.... } }

Thanks for your help谢谢你的帮助

1) The path you specified is not correct. 1) 你指定的路径不正确。 It should be not classpath*:file.csv , but classpath:file.csv .它不应该是classpath*:file.csv ,而是classpath:file.csv

2) Normally in the JAR there will be no src/main/resources/file.csv . 2)通常在 JAR 中不会有src/main/resources/file.csv The file src/main/resources/file.csv exists only in the source code.文件src/main/resources/file.csv仅存在于源代码中。 The path src/main/resources corresponds to teh root level of the JAR. Thus the file file.csv will be at the root level of your JAR.路径src/main/resources对应于 JAR 的级别。因此文件file.csv将位于 JAR 的级别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM