Spring Boot多环境配置
前言
由于项目在不同环境下配置项的值不相同,那如何使项目在不同环境下都能正常运行呢?本文探讨Spring Boot项目多环境配置的一些实践。
思路
多环境一般有开发环境、测试环境、生产环境。如果将不同环境下项目配置的值在打包时,放进包中,对于每个环境都得打一份包,并不是一种较好的做法。将包与环境中不同的配置值分离,只要打包一份就可以直接放在不同环境上运行,且各个环境的配置值可以根据需要自行调整,是一种比较理想的做法。
要点
Spring提供了profiles的概念可以帮助我们进行多环境的配置,首先看下类ConfigFileApplicationListener的getSearchLocations
// Note the order is from least to most specific (last one wins)
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";
public static final String CONFIG_LOCATION_PROPERTY = "spring.config.location";
public static final String CONFIG_ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location";
private Set<String> getSearchLocations() {
if (this.environment.containsProperty(CONFIG_LOCATION_PROPERTY)) {
return getSearchLocations(CONFIG_LOCATION_PROPERTY);
}
Set<String> locations = getSearchLocations(
CONFIG_ADDITIONAL_LOCATION_PROPERTY);
locations.addAll(
asResolvedSet(ConfigFileApplicationListener.this.searchLocations,
DEFAULT_SEARCH_LOCATIONS));
return locations;
}
从上述代码可以看出,如果有在Environment中指定了 spring.config.location 会只取该项的地址去获取配置文件,若没有指定spring.config.location,配置文件获取优先级为
- spring.config.additional-location指定的地址
- file:./config/
- file:./1.
- classpath:/config/
- classpath:/
而spring.config.name、spring.config.location和spring.config.additional-location等配置是从environment中获取的
详情可跳转 Spring Boot官方参考了解更多信息 Application Property Files
结论
上述可以得出,只要在environment(环境变量) 中指定不同的spring.config.additional-location就可以达到war包与配置文件分离的效果,常见形式如下
- jar包:jar spring-boot-sample-web.jar –spring.config.additional-location=~/config/
- war包:在tomcat中可以在${TOMCAT_HOME}/conf/catalina.properties末尾添加
#spring environment property
spring.config.additional-location=~/config/#配置文件所在文件夹
欢迎留言评论!
- file:./ 在打成jar包的springboot项目指向jar包所在目录,以war包形式在tomcat中指向startup所在的bin目录,具体可在不同环境中输出 file:./ 对应的绝对路径
new DefaultResourceLoader().getResource(“file:./”).getFile().getAbsolutePath(); ↩