在使用Spring Boot 进行开发时, 有时候我们需要让程序在运行时读取外部的配置文件application.properties.
Spring Boot 默认加载配置文件的顺序
1. jar 包所在路径的 /config 文件夹 中的 配置文件
2. 当前文件夹下的配置文件
3. classpath 中的 config 文件夹中的配置文件
4. classpath root 中的配置文件
这是spring 读取配置文件的标准顺序。如果需要让spring 读取一个自定义路径下的配置文件,可以配置“spring.config.location”这个值。
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
// set spring.config.location here if we want to run the application as a jar
public static void main(String[] args) {
new SpringApplicationBuilder(Application.class)
.sources(Application.class)
.properties(getProperties())
.run(args);
}
// set spring.config.location here if we want to deploy the application as a war on tomcat
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
return springApplicationBuilder
.sources(Application.class)
.properties(getProperties());
}
static Properties getProperties() {
Properties props = new Properties();
props.put("spring.config.location","file:///D:/file_dir/application.properties");
return props;
}
}