> 文档中心 > SpringBoot 多环境配置文件切换

SpringBoot 多环境配置文件切换

文章目录

  • 前言
  • 背景
  • 解决方案
  • 一、新建配置文件
  • 二、 服务调用测试
    • 2.1 新建调用类
    • 2.2 使用样例项目
  • 三、扩展练习
    • 3.1 使用注解标记配置,首先定义一个接口
    • 3.2 分别定义俩个实现类来实现它
    • 3.3 修改application.yml文件激活配置
    • 3.4 新增查询方法
    • 3.5 使用一个或多个配置文件及激活标记文件
      • 3.5.1 修改application.yml文件,进行属性叠加
      • 3.5.2 新增查询方法
    • 3.6 切换日志文件
      • 3.6.1 新建logback文件
    • 友情提示:jar运行指定配置
  • 总结

前言

请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i、


背景

很多时候,我们项目在开发环境和生成环境的环境配置是不一样的,例如,数据库配置,在开发的时候,我们一般用测试数据库,而在生产环境的时候,我们是用正式的数据,这时候,我们可以利用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: 9990spring:  profiles:    active: dev #选定配置#自定义默认值curvar:  context: default.curvar

application-pro.yml (开发配置)

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

application-pro.yml(生产配置)

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

二、 服务调用测试

2.1 新建调用类

@Slf4j@RestControllerpublic 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 多环境配置文件切换
SpringBoot 多环境配置文件切换
该处使用的url网络请求的数据。


三、扩展练习

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文件

项目结构
logback-pro.yml (生产日志)

<configuration debug="true">    <contextName>logback</contextName>        <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>debug</level> </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.gz</fileNamePattern>     <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">  <maxFileSize>100MB</maxFileSize>     </timeBasedFileNamingAndTriggeringPolicy>          <maxHistory>7</maxHistory> </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 #指定启动端口

总结

提示:此处只是简单举例验证,可自行扩展

参考链接