yaml语法和用法
yaml语法
1.基本写法
key: value(注意:后有一个空格)
name: luo
2.对象的写法
person:
name: value
age: value
对象的行内写法:person{name:value,age:value}
3.数组的写法
pets:
- cat
- dog
- pig
对象行内写法 pets:[cat,dog,pig]
yaml配置文件的作用 可以在实体类中注入值
根据ymal的语法,编写一个application.ymal文件
person:
name: Spring
sex: man
age: 12
maps:
hobby: basketball
color: bule
lists:
- code
- girl
dog:
name: wangcai
age: 3
我们先建立两个实体类
Dog
package com.google.pojo;
import org.springframework.stereotype.Component;
@Component//将这个类给spring托管自动注册成Bean
public class Dog {
private String name;
private int age;
public Dog() {
}
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Person
package com.google.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "person")
//@ConfigurationProperties作用:
//1.将配置文件中配置的每一个属性的值,映射到这个类中
//2.告诉springBoot将本类的所有属性和配置文件中的相关配置的属性进行绑定
//3.参数prefix='person':将配置文件中的person下面的所有属性一一对应
public class Person {
private String name;
private String sex;
private int age;
private Map maps;
private List
在springBoot自带的test进行测试
package com.google;
import com.google.pojo.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Spring01ConfigApplicationTests {
@Autowired//自动装配,前提是spring容器中存在person(前面Component已经将person注册到
//spring容器中)
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
测试结果
Person{name='Spring', sex='man', age=12, maps={hobby=basketball, color=bule}, lists=[code, girl], dog=Dog{name='wangcai', age=3}}
爆红问题
使用了ConfigrationProperties就会出现这样的问题
只需要导入一个依赖再重启就可以了
org.springframework.boot
spring-boot-configuration-processor
true