接下来我们来看看如何进行yaml配置文件值获取
可以通过https://start.spring.io/快速建立SpringBoot,并导入maven项目;
我们可以导入配置文件处理器,以后编写配置就有提示了,在Pom文件添加如下依赖
<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
建立Person类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉springboot将本类中的所有属性和配置文件中相关的配置进行绑定;
*prefix = "person"配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
这里可以通过快捷键获取相对应的set和get以及toString方法,在此省略
接着建立Dog类
public class Dog {
private String name;
private Integer age;
同样这里set和get方法以及toString方法省略
接着进行yaml文件配置
server:
port: 8081
person:
lastName: zhangsan
age: 18
boss: false
birth: 2020/11/24
maps: {k1: v1,k2: 12}
lists:
- lisi
- zhaoliu
dog:
name: 小狗
age: 12
接下来我们去测试一下看看有没有通过@ConfigurationProperties(prefix = “person”)把yaml配置文件中的值注入到容器中的Person组件中
import com.atguigu.springboot.bean.Person;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Springboot单元测试;
*
* 可以在测试期间很方便的类似编码一样进行自动注入等容器的功能
* SpringRunner是Springboot的驱动器
*/
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBoot02ConfigApplicationTests {
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
看下测试结果:
结果表明yaml配置文件中的值的确获取到了。
谈谈SpringBoot配置文件(四)