Springboot之yaml语法介绍

Springboot配置文件有两种propertis与yaml文件两种,官网推荐yaml

为啥推荐yaml,在于yaml的语法的强大及灵活,yaml语法如下:

person:
  name: laowu    #String普通键值对
  lists:          #list集合
    - a
    - b
    - c
  age: 18        #int类型普通键值对
  sex: true      #boolean类型普通键值对
  map: {k1: 100,k2 : 200}  #map集合
  dog:           #java对象
    name: ${person.name: hello}_旺财  #支持动态值,本实例最终显示dog的name值为laowu_旺财,如果找不到则name显示为 hello_旺财
    remark: 123123123

使用yaml方式

创建普通对象, 注入到spring容器,配置@ConfigurationProperties(prefix="person"),代码如下

  • 关键点@ConfigurationProperties(prefix="person") ,prefix需要与application.yaml定义的节点对应上

package com.example.demo;

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

import java.util.HashMap;
import java.util.List;

@Component
@ConfigurationProperties(prefix="person")  //关键点@ConfigurationProperties(prefix="person") ,prefix需要与application.yaml定义的节点对应上
public class TestYamlPerson {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }

    public int getAge() {
        return age;
    }

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

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    public HashMap getMap() {
        return map;
    }

    public void setMap(HashMap map) {
        this.map = map;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    private List<String> lists;
    private int age;
    private boolean sex;
    private HashMap map;
    private Dog dog;

    @Override
    public String toString() {
        return "TestYamlPerson{" +
                "name='" + name + '\'' +
                ", lists=" + lists +
                ", age=" + age +
                ", sex=" + sex +
                ", map=" + map +
                ", dog=" + dog +
                '}';
    }
}

结果测试

测试方式

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoApplicationTests {
	@Autowired
	TestYamlPerson testYamlPerson;

	@Test
	void contextLoads() {
		System.out.println(testYamlPerson);
	}

}

测试结果

Springboot之yaml语法介绍

propertis语法介绍,只支持如下语法,使用方式省略

name=aaaaa

上一篇:zdog 伪3D引擎


下一篇:shell脚本学习(三)