springboot环境配置,yml格式,不同环境切换

配置文件properties.yml格式

注意:

  • 大小写敏感
  • 数据前要有空格
  • 数据格式:对象、数组、纯量、数据格式引用${}
# 加载顺序 yml > yaml > properties
# 覆盖顺序:properties > yaml > yml,即properties中内容与其他冲突时properties有限生效。
server:
  port: 8088

# 对象
person:
  uName: 张三
  age: 20

#对象单行格式
person2: { uName: 张三, age: 20 }

# 数组格式
addr:
  - 北京
  - 上海
#数组单行格式
addr2: [ 北京, 上海 ]

#纯量
msg: 'hello \n word' # 不会转译字符,会原样输出
msg1: "hello \n word" # 会识别转译字符

#参数引用 ${}
gender: test
person3:
  uName: 张三
  gender: ${gender}

获取yml中的值

使用@Value 获取单个值
使用@Environment 获取全部
在类中直接注入@ConfigurationProperties(prefix = “person”)

@Value方式

    //    从yml中获取相应的值
//    纯量
    @Value("${msg}")
    String msg;
    @Value("${msg1}")
    String msg1;
//    对象
    @Value("${person.uName}")
    String uName;
    @Value("${person.age}")
    int age;
//    数组
    @Value("${addr[0]}")
    String addr1;

@Environment方式

@Autowired
    Environment env;
// 获取值,默认返回String类型
System.out.println(env.getProperty("msg"));
String age = env.getProperty("person2.age");
System.out.println(age);
System.out.println(env.getProperty("person2.age"));

在类中直接注入@ConfigurationProperties(prefix = “person”)

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "person")
@Component
public class Person {
    private String uName;
    private String age;
    String[] addr;

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String[] getAddr() {
        return addr;
    }

    public void setAddr(String[] addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "Person{" +
                "uName='" + uName + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

获取时候直接注入Person类就可以获取相应的值

 @Autowired
    Person person;

环境配置(指定开发或者测试环境)

profile用于不同环境切换
激活方式:

  • 文件中声明 spring.profiles.active=pro
  • 虚拟机参数 -Dspring.profiles.active=dev
  • 命令行参数 --spring.profiles.active=dev

使用properties时

可设置多个properties文件,在主文件中指明使用环境
在这里插入图片描述

#指定配置环境
spring.profiles.active=pro

使用yml时:

  • 可使用 — 隔离多个环境,在最后指明激活环境
  • 也可以在此处定义指明,也可以在运行时使用命令 --spring.profiles.active=dev指明使用环境
---
#识别顺序优先级 properties > yml > yaml
myconfig:
  localInterface: http://localhost:8089/
  autoPunchInterface: http://localhost:8088/

server:
  port: 8081

#设置开放环境
spring:
  config:
    activate:
      on-profile: dev
---

myConfig:
  localInterface: http://localhost:8089/
  autoPunchInterface: http://localhost:8088/


server:
  port: 8082

#设置生产环境
spring:
  config:
    activate:
      on-profile: pro
---

#可以在此处定义指明,也可以在运行时使用命令 --spring.profiles.active=dev指明使用环境
#激活环境
spring:
  profiles:
    active: pro

版权声明:本文为weixin_43960044原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。