SpringBoot2.X (二十二):SpringBoot 多环境配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fxbin123/article/details/82882083

一、 问题背景

在项目开发中经常有开发环境、测试环境、预发布环境、生产环境,而且一般这些环境配置会各不相同,手动改配置麻烦且容易出错,如何管理不同环境的配置参数呢?

二、多环境配置

有不了解yaml 语法的可以参考这里: https://www.jianshu.com/p/97222440cd08
在线properties 转 yaml 工具: http://www.toyaml.com/index.html

1、创建application.yml 文件,写入如下配置,模拟各个环境:

server:
  port: 8181
spring:
  application:
    name: multipart-environment
  profiles:
    active: dev   # 指定启动环境

# 开发环境
---
spring:
  profiles: dev
test:
  env: dev

# 测试环境
---
spring:
  profiles: test
test:
  env: test
  
# 仿生环境
---
spring:
  profiles: staging
test:
  env: staging
  
# 生产环境
---
spring:
  profiles: prod
test:
  env: prod

2、创建一个测试的controller : 接口打印各个环境的值

package com.fxbin.env.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * created with IntelliJ IDEA.
 * author: fxbin
 * date: 2018/9/28
 * time: 13:54
 * version: 1.0
 * description:
 */
@RestController
@RequestMapping
public class TestController {

    @Value("${test.env}")
    private String env;

    @RequestMapping("/test")
    public String testMultipartEnv(){
        return "当前启动环境为:[" + env + "]";
    }
}

3、指定启动环境为 dev
在这里插入图片描述

三、测试

项目启动之后访问我们的测试controller, 结果如下图所示:
在这里插入图片描述


示例代码地址: https://gitee.com/fxbin123/SpringBoot2Example
—— end ——

猜你喜欢

转载自blog.csdn.net/fxbin123/article/details/82882083