SpringBoot 多环境配置文件切换

背景

很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据,这时候,我们可以利用profile在不同的环境下配置用不同的配置文件或者不同的配置。

解决方案

spring boot允许你通过命名约定按照一定的格式(application-{profile}.properties)来定义多个配置文件,然后通过在application.properyies通过spring.profiles.active来具体激活一个或者多个配置文件,如果没有没有指定任何profile的配置文件的话,spring boot默认会启动application-default.properties。

一、新建配置文件

注:配置文件优先级(由高到低):
bootstrap.properties -> bootstrap.yml -> application.properties -> application.yml

此处使用.yml文件格式,在src/main/resources下新建如下文件

application.yml (主配置)

server:
  port: 9990

spring:
  profiles:
    active: dev #选定配置

#自定义默认值
curvar:
  context: default.curvar

application-pro.yml (开发配置)

#模拟开发配置
curvar:
  context: "开发配置变量"

application-pro.yml(生产配置)

#模拟生产配置
curvar:
  context: "生产配置变量"

二、 服务调用测试

2.1 新建调用类

@Slf4j
@RestController
public class IndexController {

    @Value("${curvar.context}")
    private String cusvar;

    /**
     * .
     * 使用哪一个配置
     *
     * @return
     */
    @RequestMapping("/test")
    public String test() {
        log.debug("使用:[{}]", cusvar);
        return "使用配置: " + cusvar;
    }

}

2.2 使用样例项目

打开浏览器输入:http://localhost:9990/test

SpringBoot 多环境配置文件切换

三、扩展练习

3.1 使用注解标记配置,首先定义一个接口

public interface Connector {

    String configure();
}

3.2 分别定义俩个实现类来实现它

import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("pro-db")//标记文件,环境切换
public class ProConnector implements Connector {

    @Override
    public String configure() {
        return "pro生产标记文件...";
    }
}
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

@Component
@Profile("dev-db")//标记文件,环境切换
public class DevConnector implements Connector {

    @Override
    public String configure() {
        return "dev开发标记文件...";
    }
}

3.3 修改 application.yml 文件激活配置

spring:
  profiles:
    #active: dev #选定配置
     active: pro-db #选定配置激活标记文件

3.4 新增查询方法

@Autowired
    private Connector connector; //注入

   /**
     * .
     * 使用哪一个被标记文件
     *
     * @return
     */
    @GetMapping("/proFile")
    public String proFile() {
        log.debug("使用配置文件:[{}]", connector.configure());
        return connector.configure();
    }

打开浏览器输入:http://localhost:9990/proFile

SpringBoot 多环境配置文件切换

3.5 使用一个或多个配置文件及激活标记文件

3.5.1 修改 application.yml文件,进行属性叠加

spring:
  profiles:
    include: pro,dev-db #指定配置文件及激活标记文件
    #active: pro-db #选定标记文件

3.5.2 新增查询方法

/**
     * .
     * 使用哪一个配置文件及标记文件
     *
     * @return
     */
    @GetMapping("/include")
    public String include() {
        return String.format("使用配置文件:%s,使用标记文件:%s", cusvar, connector.configure());
    }

打开浏览器输入:http://localhost:9990/include

SpringBoot 多环境配置文件切换

3.6 切换日志文件

3.6.1 新建logback文件

SpringBoot 多环境配置文件切换

logback-pro.yml (生产日志)

xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <contextName>logbackcontextName>

    <property name="log.path" value="./pro.log"/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debuglevel>
        filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} %contextName  [%thread] %-5level %logger{36} [%file : %line] - %msg%n
            pattern>
        encoder>
    appender>

    <appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.%i.gzfileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MBmaxFileSize>
            timeBasedFileNamingAndTriggeringPolicy>

            <maxHistory>7maxHistory>
        rollingPolicy>

        <encoder>
            <pattern>%date %level  [%thread] %logger{36} [%file : %line] %msg%n
            pattern>
        encoder>
    appender>

    <root level="debug">
        <appender-ref ref="console"/>
    root>

    <root level="info">
        <appender-ref ref="file"/>
    root>
    <logger name="org.springframework.scheduling" level="error"/>
    <Logger name="org.apache.catalina.util.LifecycleBase" level="error"/>
    <Logger name="org.apache.coyote.http11.Http11NioProtocol" level="warn"/>
    <Logger name="org.apache.tomcat.util.net.NioSelectorPool" level="warn"/>
    <Logger name="org.springframework" level="info"/>
    <Logger name="org.freeswitch.esl" level="warn"/>
    <logger name="java.sql" level="error"/>
    <logger name="org.mybatis" level="info"/>
    <logger name="com.example" level="debug"/>
configuration>

3.6.2 修改 application.yml 文件,配置日志属性

spring:
  profiles:
    #include: pro,dev-db #指定配置文件及激活标记文件
    #active: pro-db #选定标记文件
    active: pro #指定配置文件

#日志
logging:
   config: classpath:logback-${spring.profiles.active}.xml #本地IDEA启动配置
   #config: config/logback-${spring.profiles.active}.xml # java -jar 包启动配置

项目启动访问接口,控制台打印日志

SpringBoot 多环境配置文件切换

友情提示:jar运行指定配置

java -jar xxx.jar --spring.profiles.active=dev  #指定dev配置

java -jar xxx.jar --server.port=9090 #指定启动端口

参考链接

Original: https://www.cnblogs.com/bgyb/p/16072713.html
Author: 南国以南i
Title: SpringBoot 多环境配置文件切换

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/612303/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • CVE-2020-3452漏洞复现

    一、前言 前端时间碰到了该漏洞,记录一下! 二、漏洞介绍 该漏洞为思科ASA设备和FTD设备的未授权任意文件读取漏洞,但仅能读取到 WEB 目录下的文件,影响版本如下: Cisco…

    Linux 2023年6月8日
    0100
  • ansible -自动运维工具

    Ansible-自动运维工具 1.简介 Ansible是一个基于Python开发的配置管理和应用部署工具,现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点,Pubbe…

    Linux 2023年6月13日
    0117
  • C++ 多线程按顺序执行函数

    404. 抱歉,您访问的资源不存在。 可能是网址有误,或者对应的内容被删除,或者处于私有状态。 代码改变世界,联系邮箱 contact@cnblogs.com 园子的商业化努力-困…

    Linux 2023年6月11日
    093
  • 总结

    门诊:11张 张张是主表,主表之王是患者信息住院:12张 张张由入院登记开始,外挂处方点评一张电子病历:12张 病历概要打头来,紧接门(急)病历,急诊留观放尾中,住院病历放最后检验…

    Linux 2023年6月13日
    0118
  • 高速USB转8串口产品设计-RS232串口

    基于480Mbps 高速USB转8路串口芯片CH348,可以为各类主机扩展出8个独立的串口。使用厂商提供的VCP串口驱动程序,可支持Windows、Linux、Android、ma…

    Linux 2023年6月7日
    099
  • python爬虫爬取国家科技报告服务系统数据,共计30余万条

    python爬虫爬取国家科技报告服务系统数据,共计30余万条 按学科分类【中图分类】 共计三十余万条科技报告数据 爬取的网址:https://www.nstrs.cn/kjbg/n…

    Linux 2023年6月14日
    080
  • Windows 10 多用户同时远程登录

    win服务器版默认是支持多用户登陆的,甚至可以在主机上用不同用户自己远程登陆自己,如window server 2016。 Win10 正常情况下是不允许用户同时远程的,即一个用户…

    Linux 2023年6月14日
    0145
  • 配置免密登陆服务器

    前言 原来自己学习的时候在阿里云买自己的学习机,一台主机自己瞎折腾。但是参加工作以后管理的主机越来越多了,上服务器看的频率也越来越频繁,虽然有时候shell管理工具可以很方便的保存…

    Linux 2023年5月27日
    0144
  • 设计模式——面向对象设计原则

    面向对象设计原则 都是为了高内聚低耦合原则。编程时基本都要遵守 分类原则:一种人只干一种事。 举例:(比较简单就不代码了) 人可以干的事情有很多:敲代码、唱歌、跳舞、打篮球&#82…

    Linux 2023年6月7日
    0163
  • shell升级完整记录

    [root@localhost bash-4.3.30]# cat Makefile |grep prefix prefix = /usr/local exec_prefix = …

    Linux 2023年5月28日
    085
  • redis分布式之codis,twemproxy

    一、codis 1.什么是Codis? Codis 是一个分布式 Redis 解决方案, 对于上层的应用来说, 连接到 Codis Proxy 和连接原生的 Redis Serve…

    Linux 2023年5月28日
    090
  • Java刷题笔记7.25

    一个类构造方法的作用是什么? &#x4E3B;&#x8981;&#x662F;&#x5B8C;&#x6210;&#x5BF9;&am…

    Linux 2023年6月7日
    0120
  • Nginx服务的搭建与配置

    Nginx服务的搭建与配置 一、关闭防火墙并安装epel源 1、关闭selinux ①修改selinux的配置文件 [root@localhost ~]# vim /etc/sel…

    Linux 2023年6月7日
    0122
  • ADB和Fastboot最新版的谷歌官方下载链接

    最新ADB及Fastboot版本说明(SDK Platform Tools 版本说明) ADB和Fastboot for Windows ADB和Fastboot for Mac …

    Linux 2023年6月7日
    0106
  • Ubuntu18.04 显卡驱动安装(解决各种疑难杂症)

    步骤 下载驱动 准备工作 进行安装 检查安装 下载驱动 首先,我们需要从官网下载显卡驱动。 [En] First of all, we need to download the v…

    Linux 2023年5月27日
    0108
  • Redis info参数总结(转)

    可以看到,info的输出结果是分几块的,有Servers、Clients、Memory等等,通过info后面接这些参数,可以指定输出某一块数据。 我刚开始在Gentoo上装的默认版…

    Linux 2023年5月28日
    0130
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球