• springboot+maven多环境动态配置,以及编译失败的解决方案


    一、前言

    在我们的项目开发过程中一般会有多套的环境,比如比较常见的会有三套: dev (研发环境),test(测试环境),prod(生产环境)。
    在这里插入图片描述
    application.yml 是主配置文件,当在不同的环境中需要激活不同环境的配置文件,改动active 后面的value即可。但是这种方式有个弊端,需要每次手动改动才生效,不灵活,有没有一个比较简便的方式呢?其实maven给我们提供一种在编译阶段时动态修改激活环境的参数的方法。

    二、springboot+maven多环境动态配置

    其实很简单,只需要2步即可

    2.1 修改application.yml

    application.yml 中的active哪一行改成:

    spring:
      profiles:
        active: @profiles.active@
    
    • 1
    • 2
    • 3

    2.2 maven中添加profile配置

        
        <profiles>
            
            <profile>
                <id>devid>
                <properties>
                    
                    <profiles.active>devprofiles.active>
                properties>
                
                <activation>
                    <activeByDefault>trueactiveByDefault>
                activation>
            profile>
            
            <profile>
                <id>testid>
                <properties>
                    <profiles.active>testprofiles.active>
                properties>
            profile>
            
            <profile>
                <id>prodid>
                <properties>
                    <profiles.active>prodprofiles.active>
                properties>
            profile>
        profiles>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    在maven中加完以上配置,就可以在idea 的右侧看到dev的配置已经激活。
    在这里插入图片描述
    点击小锤子进行编译,会发现application.yml中的 @profiles.active@ 编译完以后 就被替换成 dev
    在这里插入图片描述

    2.3 编译时如何动态切换呢

    方法一:通过idea的可视化界面进行操作
    在这里插入图片描述
    方案二:通过maven 编译命令指定参数

    mvn compile -P prod
    
    • 1

    在这里插入图片描述
    可以看到编译完成以后的文件 active 已经变成 prod 了。

    2.4 无法编译成功或正常启动的解决方案

    使用 idea的小锤子进行编译。或者直接启动项目可能会出现 无法替换掉 application.yml 中active: @profiles.active@,建议使用 2.3 中的 方案一和方案二进行编译,编译成功以后,只要不执行maven clean 命令则就一直能用。

  • 相关阅读:
    Nginx(六) Nginx location 匹配顺序及优先级深究(亲测有效)
    中小商家,也能在抖音电商找到星辰大海
    【简单了解一下红黑树】
    定制chromium中window对象添加函数
    Python 自动化Web测试
    MyBatis-动态SQL
    聊聊linux的文件缓存
    慌了,面试官问我G1垃圾收集器
    安徽省专业技术类职业资格与职称对应表
    弘辽科技:淘宝没提升销量就没流量吗?怎么挽救?
  • 原文地址:https://blog.csdn.net/weter_drop/article/details/134400886