欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > SpringBoot服务多环境配置

SpringBoot服务多环境配置

2025/2/25 6:00:54 来源:https://blog.csdn.net/m0_63451467/article/details/143885159  浏览:    关键词:SpringBoot服务多环境配置

一个项目的的环境一般有三个:开发(dev)、测试(test)、生产(proc),一般对应三套环境,三套配置文件。
像下面这样直接写两个配置文件是不行的。

application.ymlserver:port: 8080
application-dev.ymlspring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCusername: rootpassword: root

SpringBoot多环境配置有两种方式,一种是在配置文件中指定环境,一种是用maven中指定文件

通过配置文件

使用spring.profiles.active配置项

application.ymlserver:port: 8080
spring:profiles:active: dev
application-dev.ymlspring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCusername: rootpassword: root

通过maven

通过maven控制环境有个好处就是可以直接通过idea右侧的maven管理功能控制项目环境

pom.xml<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
...<build><resources><resource><directory>src/main/resources</directory><excludes><exclude>application*.yml</exclude></excludes></resource><resource><directory>src/main/resources</directory><filtering>true</filtering><includes><include>application.yml</include><include>application-${env}.yml</include></includes></resource></resources></build><profiles><profile><id>dev</id><activation><!-- 默认激活的环境 --><activeByDefault>true</activeByDefault></activation><properties><env>dev</env></properties></profile><profile><id>prod</id><properties><env>prod</env></properties></profile></profiles></project>
application.ymlspring:profiles:active: @env@
server:port: 8080
application-dev.ymlspring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTCusername: rootpassword: root

版权声明:

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

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

热搜词