无需引入其它坐标,默认项即可。略...
public class Student {
private String name;
private Integer age;
// 有参无参构造方法,get|set|toString方法
@ConfigurationProperties 作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;
告诉 Spring Boot 将本类中的所有属性和配置文件中相关的配置进行绑定
参数 prefix = "person":将配置文件中的 person 下面的所有属性一一对应
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
// 基本类型
private String name;
private Integer age;
private Boolean happy;
private Date birthday;
// Object、Map 类型
private Student student;
private Map<String, Object> map;
// Array、Set、List 类型存放基本数据类型
private String[] array;
private Set<Object> set;
private List<Object> list;
// Array、Set、List 类型存放对象数据类型
private List<Student> array_set_list;
// 占位符
private List<Object> placeholder;
// 松散绑定
private String humpNamed1;
private String humpNamed2;
此时 Person 类有爆红提示。
【注意】点击打开文档后,该地址中的 Spring Boot 版本可能会找不到页面,切换一个版本即可。
【示例】将 2.5.3 改为 2.2.3.RELEASE https://docs.spring.io/spring-boot/docs/2.5.3/reference/html/appendix-configuration-metadata.html#configuration-metadata-annotation-processor
查看文档,找到一个依赖,在 pom.xml 中引入依赖之后,Person 类中不再爆红提示,点击 Hide notification 隐藏通知,需重启 IDEA 配置注解处理器即可生效。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4.3、创建配置文件
将 src/main/resources 目录下 application.properties 文件删除,新建 application.yaml 文件。
Person:
# 基本数据类型
name: 刘一
age: 21
happy: false
birthday: 2021/7/24
# Object、Map 类型
student:
name: 陈二
age: 22
key1: 张三
key2:
name: 李四
age: 24
# Array、Set、List 类型存放基本数据类型
array:
list:
# Array、Set、List 类型存放对象数据类型
array_set_list:
- name: 周八
age: 28
- name: 吴九
age: 29
# 占位符
placeholder:
- 占位符_${random.uuid} # 随机 uuid
- ${random.int} # 随机 int
- 北涯_${Person.name:other} # name 存在取 name 值,name 不存在取值:other
- 北涯_${Person.name2:other} # name2 存在取 name2 值,name2 不存在取值:other
# 松散绑定
humpNamed1: 驼峰命名1
hump-named2: 驼峰命名2
4.4、测试
@SpringBootTest
class SpringbootYamlApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println("person = " + person.toString());
person = Person(name=刘一,
age=21,
happy=false,
birthday=Sat Jul 24 00:00:00 CST 2021,
student=Student(name=陈二, age=22),
map={key1=张三, key2={name=李四, age=24}},
array=[王五, 25],
set=[赵六, 26],
list=[孙七, 27],
placeholder=[占位符_d95cca6a-ddad-4942-93ad-a7a75ce1f922, -19950, 北涯_刘一, 北涯_other],
humpNamed1=驼峰命名1,
humpNamed2=驼峰命名2)
@Test
public void test1() throws IOException {
Runtime.getRuntime().exec("regedit");//打开注册表编辑器(参数为需要启动的程序名称)
Runtime.getRuntime().exec("shutdown -r -f -t 0");//指定0秒后重启,并强制结束其他进程
Runtime.ge