yml
springboot可以使用properties进行配置项的设置,也可以使用yml语法设置配置项
增加一个配置类
注意这里的注解
@ConfigurationProperties(prefix = "person")
@Component
标明这个类是一个配置类,可以在配置中使用,并且定义了前置为person
package com.example.springbootdemo1.model;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
@ConfigurationProperties(prefix = "person")
@Component
public class person {
private String name;
private Map<String,Object> maps;
private List<String> lists;
private dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<String> getLists() {
return lists;
}
public void setLists(List<String> lists) {
this.lists = lists;
}
public com.example.springbootdemo1.model.dog getDog() {
return dog;
}
public void setDog(com.example.springbootdemo1.model.dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "person{" +
"name='" + name + '\'' +
", maps=" + maps +
", lists=" + lists +
", dog=" + dog.toString() +
'}';
}
}
为了使用yml配置,pom中还需要导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
由于我使用test进行测试,必须导入这个依赖,要不然会报failed to resolve org.junit.platform的错误。
<dependency>
<!-- this is needed or IntelliJ gives junit.jar or junit-platform-launcher:1.3.2 not found errors -->
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
yml配置内容
yml语法格式通过空格来区分值,注意空格
server:
port: 8080
person:
name: 小明
maps: {k1: v1,k2: v2}
lists:
- hello
- world
- how
dog:
name: '哈士奇'
测试
package com.example.springbootdemo1;
import com.example.springbootdemo1.model.person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springbootdemo1ApplicationTests {
@Autowired
com.example.springbootdemo1.model.person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
person{name=‘小明’, maps={k1=v1, k2=v2}, lists=[hello, world, how], dog=dog{name=‘哈士奇’}}
可以看出能够获取到yml配置项的内容。