我必须从类路径之外加载文件。 位置取决于env属性:
/location/file
)加载文件最好的方法是什么?
答案 0 :(得分:1)
可能的解决方案是使用配置属性和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()
方法,该方法允许您检索文件,但除此之外,它还包含其他几种有用的方法。