[英]Spring boot - load file from outside classpath
我必须从类路径之外加载文件。 位置取决于env属性:
/location/file
)加载文件 最好的方法是什么?
一种可能的解决方案是使用配置属性和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()
方法,该方法允许您检索文件,但除此之外,它还包含其他几个有用的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.