欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 明星 > spring boot设置多环境的配置文件

spring boot设置多环境的配置文件

2025/4/3 2:11:00 来源:https://blog.csdn.net/qq_38313548/article/details/142177605  浏览:    关键词:spring boot设置多环境的配置文件

目录

  • 说明
  • 规划
  • 步骤
  • 案例
    • application.yml
    • application-dev.yml
    • application-test.yml
    • application-prod.yml

说明

在项目开发过程中,回有开发环境、测试环境、生产环境等等。如果所有环境的配置都放在application.yml中并且需要打包到不同的环境中时,修改application.yml同一个文件时会出现遗漏,或者是配置错误的情况。
例如不通过环境下的数据库配置、项目启动的端口号等等。
此时我们可以多创建几个不同环境下的配置文件使用,需要让项目在打包时、运行时 自动去识别需要使用的配置文件。

规划

本案例主要规划为开发环境、测试环境、生产环境。为这三个环境创建三个配置文件。如以下表:

环境文件名称
开发环境application-dev.yml
测试环境application-test.yml
生产环境application-prod.yml

步骤

  1. 项目创建后,创建配置文件,如下:
  • application.yml : springboot项目能识别的配置文件。必须存在。
  • application-dev.yml : 自定义的开发环境配置文件。其中主要配置开发环境中使用的配置内容
  • application-test.yml :自定义的测试环境配置文件。其中主要配置测试环境中使用的配置内容
  • application-prod.yml :自定义的生产环境配置文件。其中主要配置生产环境中使用的配置内容
  1. 修改项目的pom.xml
    在项目的pom.xml中加入以下配置:
 <!-- 配置文件管理 --><profiles><!-- 开发环境使用的配置文件 --><profile><id>dev</id><activation><!-- 默认启动时使用开发环境配置启动 --><activeByDefault>true</activeByDefault></activation><properties><!-- environment 标签为自定义标签,dev值与上面的id标签值一致,且与配置文件名称中的 -dev 一致  environment标签的名称会在application.yml 中使用。--><environment>dev</environment></properties></profile><!-- 测试环境使用的配置文件 --><profile><id>test</id><properties><environment>test</environment></properties></profile><!-- 生产环境使用的配置文件 --><profile><id>prod</id><properties><environment>prod</environment></properties></profile></profiles>

此时idea中的maven中就会出现配置的三个环境的选项。
当我们需要打包或者需要以哪个环境的配置文件启动项目时,再此勾选后运行或者打包项目即可。
在这里插入图片描述
3. 在application.yml 配置中新增加以下的配置

spring:profiles:# 开始和结尾使用@符号# environment为pom.xml中步骤2中配置的自定义标签名称。active: @environment@

案例

application.yml

此配置中可以放三个环境中相同配置的内容

# 项目端口是公共的,即三个环境中配置的端口是一致的,可以放在此配置文件中
server:port: 8081spring:profiles:# 开始和结尾使用@符号# environment为pom.xml中步骤2中配置的自定义标签名称。active: @environment@

application-dev.yml

开发环境下的配置文件

spring:datasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/zhangDev?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=trueusername: rootpassword: 123456

application-test.yml

测试环境下的配置文件

spring:datasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://192.168.83.156:3306/zhangTest?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=trueusername: rootpassword: ajhbie234

application-prod.yml

生产环境下的配置文件

spring:datasource:druid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxx.xx.xxx.xxx:3306/usersystem?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=trueusername: userapipassword: ajue@zhang2258

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词