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)

大家都在看

  • Java 8 中的 Stream 遍历树形结构

    树形结构数据处理 public class TreeDemo { public static void main(String[] args) { testtree(); } pu…

    Linux 2023年6月7日
    0108
  • 在c/c++中输入彩色日志输出,带有带有颜色的打印

    在c/c++中输入彩色日志输出,带有带有颜色的打印 #ifndef __PTINTCOLOR_H #define __PTINTCOLOR_H #include #ifndef L…

    Linux 2023年6月14日
    0128
  • fork创建进程的步骤___Spring-boot-Starter启动器和其加载的过程___redis怎么监视正在执行的命令

    fork创建进程的步骤 我们都知道,在Linux中调用fork()函数,会创建一个子进程,那么在创建这个子进程的过程中,发生了些什么事情? 首先,我们要知道,fork()函数其实是…

    Linux 2023年5月28日
    0108
  • linux 命令 df -h 查不到新添加的硬盘

    云平台:腾讯云系统:ubuntu 20.04 第一部分:缘由 1、我的一台云服务器上挂载了两块硬盘。一块 50G 系统盘、一块 400G 数据盘。然后我查询目前在 Linux 系统…

    Linux 2023年5月27日
    0323
  • Android XML: Multiple button layout

    The layout : The xml code : 😃(before using this code, you should create your drawable xml …

    Linux 2023年6月13日
    096
  • 服务管理与通信,基础原理分析

    涉及轻微的源码展示,可放心参考; 一、基础简介 服务注册发现是微服务架构中最基础的能力,下面将从源码层面分析实现逻辑和原理,在这之前要先来看下依赖工程的基础结构,涉及如下几个核心组…

    Linux 2023年6月14日
    0134
  • map_set使用说明

    map_set使用说明 map的底层结构大致是一个哈希表,set的底层结构大致是一个红黑树 不代表全部! set #include"map_set.h" //s…

    Linux 2023年6月13日
    088
  • Snap Build Your Own Block修炼之道-添加自定义类别

    Snap Build Your Own Block自我修炼方法:1、所有的面向对象,其实是对面向过程的抽象过程而已; 2、面对别人的开源项目时,需要找准源头(即项目运行的起点,当然…

    Linux 2023年6月6日
    093
  • Hadoop 调优

    Hadoop 调优 HDFS 调优 hdfs-site.xml 1. hadoop 文件块大小,通常为 128MB 或 256MB dfs.block.size 134217728…

    Linux 2023年6月8日
    089
  • Redis分布式锁实战

    背景 目前开发过程中,按照公司规范,需要依赖框架中的缓存组件。不得不说,做组件的大牛对CRUD操作的封装,连接池、缓存路由、缓存安全性的管控都处理的无可挑剔。但是有一个小问题,该组…

    Linux 2023年5月28日
    089
  • 笔记:Java集合框架(一)

    Java集合框架(一) Collection接口 继承结构 Iterator接口 Iterator接口定义了迭代器的基本方法: java;gutter:true; hasNext(…

    Linux 2023年6月14日
    072
  • Linux 命令行设置网络代理

    echo $SHELL/usr/bin/zsh 根据当前的shell类型来设置,我这里以zsh为例,vim ~/.zshrc export ALL_PROXY=”htt…

    Linux 2023年6月6日
    0186
  • SSH升级版本–8.2p1

    前期准备 执行yum update openssh先升级下. 反正官方提供的这种升级是没问题的。如果之前手动编译操作过openssh的升级,变更了默认配置文件路径什么的请自行测试。…

    Linux 2023年6月8日
    084
  • WPF 界面打不开提示 System.ArithmeticException Overflow or underflow in the arithmetic operation 异常

    本文告诉大家如何解决界面打不开,抛出 System.ArithmeticException: Overflow or underflow in the arithmetic ope…

    Linux 2023年6月6日
    076
  • Centos 7 升级内核

    【背景说明】 在公司进行部署产品时,发公司内部的服务内核资源并不能满足于产品部署条件,于是我和内核就进行了一场风花雪月般的交互,在操作前,本人小白一枚,就在浩瀚的互联网海洋中搜索升…

    Linux 2023年5月27日
    095
  • shell编程-杨辉三角简单实现

    shell编程-杨辉三角问题: 概述:中国古代数学家在数学的许多重要领域中处于遥遥领先的地位。中国古代数学史曾经有自己光辉灿烂的篇章,而杨辉三角的发现就是十分精彩的一页。杨辉三角形…

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