Spring Boot:yaml学习笔记
在Spring Boot中,一般用yaml代替原来的peoperties文件来进行数据交互。
Spring Boot能自动识别的配置文件名:application.yaml或application.properties
yaml语法
# 普通键值对,分号后面一定要加一个空格
key: value
# 对象,对象的属性一定要设置在对象后(回车+空格)
Person:
name: xiaoming
age: 1
# Map集合或对象行内写法
map: {k1: v1,k2: v2}
# List集合或数组
lists:
- code
- music
- girl
# 数组行内写法
Array: [cat,dog,pig]
yaml属性绑定类
用@ConfigurationProperties(prefix = “”)注解的类绑定yaml中的属性
package com.huang.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
public Person() {
}
public Person(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
this.name = name;
this.age = age;
this.happy = happy;
this.birth = birth;
this.maps = maps;
this.lists = lists;
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getHappy() {
return happy;
}
public void setHappy(Boolean happy) {
this.happy = happy;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", happy=" + happy +
", birth=" + birth +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog +
'}';
}
}
person:
name: xiaoming
age: 21
happy: false
birth: 1111/11/11
maps: {k1: v1,k2: v2}
lists:
- code
- music
- girl
dog:
name: 来福
age: 36
IDEA注解类上红色提示消除办法:
导入如下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
yaml中springboot多环境配置
server:
port: 8081
spring:
profiles:
active: test
# 选中的环境
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: test