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/684905/

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

(0)

大家都在看

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