栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

1.SpringBoot的yml多环境配置3种方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

1.SpringBoot的yml多环境配置3种方法

目录

方式一:多个yml文件

  步骤一、创建多个配置文件

  步骤二、applicaiton.yml中指定配置

方式二: 单个yml文件

方式三:在pom.xml中指定环境配置

步骤一、创建多个配置文件

步骤二、在application.yml中添加多环境配置属性

步骤三、在pom.xml中指定使用的配置 

避坑:不能识别符号@

总结:


方式一:多个yml文件

  步骤一、创建多个配置文件
application.yml      #主配置文件
application-dev.yml  #开发环境的配置
application-prod.yml #生产环境的配置
application-test.yml #测试环境的配置

  步骤二、applicaiton.yml中指定配置

在application.yml中选择需要使用的配置文件(当选择的文件和application.yml文件存在相同的配置时,application.yml中的配置会被覆盖掉)

spring:
 profiles:
   active: dev #需要使用的配置文件的后缀

方式二: 单个yml文件
#激活dev环境配置
spring:
  profiles.active: dev


# 开发环境配置
spring:
  profiles: dev
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/dev?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
server:
  port: 8080


# 测试环境配置
spring:
  profiles: test
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: test
    driver-class-name: com.mysql.jdbc.Driver
server:
  port: 88



# 生产环境配置
spring:
  profiles: prod
  datasource:
    url: jdbc:mysql://localhost:3306/prod?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    username: root
    password: prod
    driver-class-name: com.mysql.jdbc.Driver
 server:
  port: 99

  配置默认的profile为dev,其他环境可以通过指定启动参数来使用不同的profile,比如:
 测试环境:java -jar 项目.jar --spring.profiles.active=test
 生产环境:java -jar 项目.jar --spring.profiles.active=prod

方式三:在pom.xml中指定环境配置

步骤一、创建多个配置文件
application.yml      #主配置文件
application-dev.yml  #开发环境的配置
application-prod.yml #生产环境的配置
application-test.yml #测试环境的配置

步骤二、在application.yml中添加多环境配置属性
#多环境配置
  profiles:
    active: @profiles.active@

步骤三、在pom.xml中指定使用的配置 
   
        
            dev
            
                
                true
            
            
                dev
            
        

        
            prod
            
                prod
            
        

        
            test
            
                test
            
        
    

true配置为true则激活对应profile的配置。

或如图所示,在maven->profiles下勾选动态激活需要使用的配置

避坑:不能识别符号@

在步骤二中配置的@profiles.active@,启动会报异常,不能识别@符号。解决方法:

在pom.xml中设置filtering为true

     
         
            
                src/main/resources
                true 
                
                    **/*.*
                
            
        
  

总结:

三种方式都可以实现多环境的配置。在application.yml主配置文件中做项目通用的配置,在其他配置文件中做不同环境下的配置,以避免重复配置的情况。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/354127.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号