配置文件-yml的用法

同以前的 properties 用法,springboot 采用 yml 配置文件。

基本语法

  • key: value;kv之间有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • '#'表示注释
  • 字符串无需加引号,如果要加,单引号表示字符串内容会被转义 、双引号表示字符串内容不转义

数据类型

  1. 字面量:单个的、不可再分的值。date、boolean、string、number、null

k: v

  1. 数组:一组按次序排列的值。array、list、queue

k: [v1,v2,v3]

或者

k:
  - v1
  - v2
  - v3

  1. 对象:键值对的集合。map、hash、set、object

k: {k1:v1,k2:v2,k3:v3}

或者

k:
  k1: v1
  k2: v2
  k3: v3

示例

application.yml:

person:
  userName: zhangsan
  boss: false
  birth: 2019/12/12 20:12:33
  age: 18
  pet:
    name: tomcat
    weight: 23.4
  interests: [篮球,游泳]
  animal:
    - jerry
    - mario
  salarys: [3999,4999.98,5999.99]
  pets: [{name: pet1,weight: 47},{name: pet2,weight: 50}]
  score:
    english:
      first: 30
      second: 40
      third: 50
    math: [131,140,148]
    chinese: {first: 128,second: 136}
  allPets:
    sick:
      - {name: tom}
      - {name: jerry,weight: 47}
    health: [{name: mario,weight: 47}]

配置类Person:

@Data
@Component
@ConfigurationProperties("person")
public class Person {
    private String userName;
    private Boolean boss;
    private Date birth;
    private Integer age;
    private Pet pet;
    private String[] interests;
    private List<String> animal;
    private Set<Double> salarys;
    private List<Pet> pets;
    private Map<String, Object> score;
    private Map<String, List<Pet>> allPets;

    @Override
    public String toString() {
        return "Person{" +
                "userName='" + userName + '\'' +
                ",\n boss=" + boss +
                ",\n birth=" + birth +
                ",\n age=" + age +
                ",\n pet=" + pet +
                ",\n interests=" + Arrays.toString(interests) +
                ",\n animal=" + animal +
                ",\n salarys=" + salarys +
                ",\n pets=" + pets +
                ",\n score=" + score +
                ",\n allPets=" + allPets +
                '}';
    }
}

依赖类Pet:

@Data
public class Pet {
    private String name;
    private Double weight;
}

启动类:

@SpringBootApplication
public class App 
{
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(App.class, args);
		
        Person person = (Person) context.getBean("person");
        System.out.println(person);

    }
}

运行结果:

Person{userName='zhangsan',
 boss=false,
 birth=Thu Dec 12 20:12:33 CST 2019,
 age=18,
 pet=Pet(name=tomcat, weight=23.4),
 interests=[篮球, 游泳],
 animal=[jerry, mario],
 salarys=[3999.0, 4999.98, 5999.99],
 pets=[Pet(name=pet1, weight=47.0), Pet(name=pet2, weight=50.0)],
 score={english={first=30, second=40, third=50}, math={0=131, 1=140, 2=148}, chinese={first=128, second=136}},
 allPets={sick=[Pet(name=tom, weight=null), Pet(name=jerry, weight=47.0)], health=[Pet(name=mario, weight=47.0)]}}

你可能感兴趣的:(SpringBoot,spring,boot)