当前位置:   article > 正文

SpringBoot--配置文件--active/include--多环境/公共配置_springboot include

springboot include

原文网址:SpringBoot--配置文件--active/include--多环境/公共配置_IT利刃出鞘的博客-CSDN博客

简介

说明

本文介绍SpringBoot如何切换多环境(开发、测试、生产)以及如何引入公共的配置文件

application.yml的spring.profiles.active用于切换多环境(选择目前激活的是哪个环境),spring.profiles.include用于引入公共的配置文件。

application.yml简单配置示例

  1. # 服务器配置
  2. server:
  3. port: 8082
  4. # spring配置
  5. spring:
  6. datasource:
  7. url: jdbc:mysql://localhost:3306/DatebaseName
  8. username: root
  9. password: 123
  10. driverClassName: com.mysql.jdbc.Driver

多环境(active)

简介

我们一般将开发(dev),测试(test),生产(prod)的配置写到不同的配置文件里边,运行时通过spring.profiles.active来选择使用哪个配置。

java命令指定参数

法1:使用-D(推荐)

  • java -Dspring.profiles.active=dev -jar test-1.0.0-SNAPSHOT.jar
  • -Dxxx=yyy必须在-jar之前
  • 此法增加的参数被设置到应用的系统属性中,可通过System.getProperty(“server.port”)获取

法2:使用--

  • java -jar test-1.0.0-SNAPSHOT.jar --spring.profiles.active=dev
  • --xxx=yyy必须在-jar之后
  • 此法增加的参数属于命令行参数,会作为SpringBoot启动的main方法的String[] args参数。
  • 有时本方法在Windows下无效。

spring.profiles.active 和 spring.profiles.include 区别

spring.profiles.active 和 spring.profiles.include 有什么区别呢?笔者认为主要是语意上的区别,实际使用效果基本相同。active 是与环境有关的,include 是与环境无关的。

实际使用,只有下边这一处区别:

The properties from spring.profile.include override default properties. The properties from active profiles override spring.profile.include and default properties.

即:spring.profile.include的属性会覆盖默认属性,spring.profiles.active会覆盖spring.profile.include和默认属性。

方案1:多个配置文件

application.yml

  1. spring:
  2. profiles:
  3. #激活开发环境
  4. active: dev
  5. spring:
  6. application:
  7. name: order

application-dev.yml 

  1. #开发环境配置
  2. spring:
  3. profiles: dev
  4. server:
  5. port: 8080

application-prod.yml 

  1. #生产环境配置
  2. spring:
  3. profiles: prod
  4. server:
  5. port: 8082

方案2:使用---

例如:

application.yml

  1. spring:
  2. profiles:
  3. #激活开发环境
  4. active: dev
  5. spring:
  6. application:
  7. name: order
  8. ---
  9. #开发环境配置
  10. spring:
  11. profiles: dev
  12. server:
  13. port: 8080
  14. ---
  15. #生产环境配置
  16. spring:
  17. profiles: prod
  18. server:
  19. port: 8082

新版本(SpringBoot2.4.2及之后)写法: 

  1. spring:
  2. profiles:
  3. #激活开发环境
  4. active: dev
  5. spring:
  6. application:
  7. name: order
  8. ---
  9. #开发环境配置
  10. spring:
  11. config:
  12. activate:
  13. on-profile: dev
  14. server:
  15. port: 8080
  16. ---
  17. #生产环境配置
  18. spring:
  19. config:
  20. activate:
  21. on-profile: prod
  22. server:
  23. port: 8082

拆出(include)

上边是文章的部分内容,为便于维护,全文已转移到此网址:SpringBoot-配置文件的active/include-多环境/公共配置 - 自学精灵

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/991967
推荐阅读
相关标签
  

闽ICP备14008679号