Spring Boot多环境配置

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,配置文件获取优先级为

  1. spring.config.additional-location指定的地址
  2. file:./config/
  3. file:./1.
  4. classpath:/config/
  5. 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/#配置文件所在文件夹

欢迎留言评论!


  1. file:./ 在打成jar包的springboot项目指向jar包所在目录,以war包形式在tomcat中指向startup所在的bin目录,具体可在不同环境中输出 file:./ 对应的绝对路径
    new DefaultResourceLoader().getResource(“file:./”).getFile().getAbsolutePath();
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值