SpringBoot之多环境开发配置

1 多环境开发配置

问题导入

在实际开发中,项目的开发环境、测试环境、生产环境的配置信息是否会一致?如何快速切换?

1.1 多环境启动配置
  • yaml文件多环境启动

不同环境使用—隔开

在这里插入图片描述
示例代码:

spring:
  profiles:
    active: dev

#生产环境
---
spring:
  profiles: pro
server:
  port: 8081
#开发环境
---
spring:
  profiles: dev
server:
  port: 8082
#测试环境
---
spring:
  profiles: test
server:
  port: 8083
  • properties文件多环境启动

不同环境使用文件名后缀区分

#主启动配置文件 application.properties
spring.profiles.active=pro
#环境分类配置文件 application-pro.properties
server.port=80
#环境分类配置文件 application-dev.properties
server.port=81
#环境分类配置文件application-test.properties
server.port=82

文件目录

在这里插入图片描述

1.2 多环境启动命令格式
  • 带参数启动SpringBoot
java –jar springboot.jar --spring.profiles.active=test
java –jar springboot.jar --server.port=88
java –jar springboot.jar --server.port=88 --spring.profiles.active=test

在这里插入图片描述

1.3 多环境开发控制

Maven与SpringBoot多环境兼容(步骤)

①:Maven中设置多环境属性

<profiles>
    <profile>
        <id>dev_env</id>
        <properties>
            <profile.active>dev</profile.active>
        </properties>
          <!--设置默认生效-->
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
  
    <profile>
        <id>pro_env</id>
        <properties>
            <profile.active>pro</profile.active>
        </properties>
    </profile>
    <profile>
        <id>test_env</id>
        <properties>
            <profile.active>test</profile.active>
        </properties>
    </profile>
</profiles>

②:SpringBoot中引用Maven属性

在这里插入图片描述

③:执行Maven打包指令

  • Maven指令执行完毕后,生成了对应的包,其中类参与编译,但是配置文件并没有编译,而是复制到包中

在这里插入图片描述

  • 解决思路:对于源码中非java类的操作要求加载Maven对应的属性,解析${}占位符

④:对资源文件开启对默认占位符的解析

<build>
    <plugins>
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                <encoding>utf-8</encoding>
                        <!--设置为true--> <useDefaultDelimiters>true</useDefaultDelimiters>
            </configuration>
        </plugin>
    </plugins>
</build>

也可以将${profile.actice}改为@profile.active@

  • Maven打包加载到属性,打包顺利通过

在这里插入图片描述

4. 配置文件分类

问题导入

SpringBoot的配置文件可以放在项目的哪些地方?

在这里插入图片描述

java –jar springboot.jar --spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima --server.tomcat.connection-timeout=-1 ... ...
  • SpringBoot中4级配置文件

    1级: file :config/application.yml 【最高】

    2级: file :application.yml

    (jar包和application.yml在同一目录)

    在这里插入图片描述

    3级:classpath:config/application.yml

    4级:classpath:application.yml 【最低】

    (也就是resources下的application.yml)

  • 作用:

    1级与2级留做系统打包后设置通用属性

    3级与4级用于系统开发阶段设置通用属性

  • 19
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值