【发布时间】:2018-12-19 19:34:34
【问题描述】:
我必须从我的类路径之外加载文件。 位置取决于环境属性:
- 在开发属性中我想从资源文件夹加载文件
- 在产品属性中,我想从路径 (
/location/file) 加载文件
最好的方法是什么?
【问题讨论】:
标签: java spring spring-boot
我必须从我的类路径之外加载文件。 位置取决于环境属性:
/location/file) 加载文件最好的方法是什么?
【问题讨论】:
标签: java spring spring-boot
一个可能的解决方案是使用配置属性和Resource。例如,像这样定义您的属性:
@ConfigurationProperties(prefix = "app")
public class SomeProperties {
private Resource file;
// Getters + Setters
}
然后通过在任何类上使用 @EnableConfigurationProperties 注释来启用您的配置属性,例如您的主类:
@SpringBootApplication
@EnableConfigurationProperties(SomeProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
要配置文件位置,可以在开发中使用如下:
app.file=classpath:test.txt
在生产环境中你可以使用:
app.file=file:/usr/local/test.txt
现在您可以在任何其他服务中自动装配SomeProperties 类。 Resource 类有一个 getFile() 方法,允许您检索文件,但除此之外,它还包含其他几个有用的方法。
【讨论】:
File/Resource 尚不存在,我该如何创建它? (例如第一次运行时创建文件)