详细内容见官方文档Common Application Properties
使用application.yaml进行简单配置
第一步:创建WebDemo
创建一个SpringBoot的WebDemo,创建WebDemo具体步骤—>如何创建一个SpringBoot的WebDemo】笔记方法二使用Spring Initializr创建一个Spring Boot项目
按照上述链接笔记中的步骤创建好WebDemo后测试正常运行后再进行下面的步骤,
此时项目的默认端口号应该为8080
第二步:创建application.yaml配置文件
操作步骤: 选中resources文件夹—>鼠标右键—>选择New—>file—>application.yaml
注意:
此时的项目中是有两个配置文件的,application.properties和application.yaml到底那个生效呢?都生效吗?只有其中一个生效?
第三步:验证自己创建的yaml文件是否生效
使用application.yaml配置项目的端口号.因为端口号默认是8080,现在我们通过yaml文件修改端口号来验证配置是否生效。
在application.yaml文件中添加配置
修改项目端口号
server:
port: 8088
如下图所示,此时application.properties和application.yaml中的内容,application.properties中什么都没有,application.yaml中配置了端口号8088
测试:
- 启动SpringBoot项目
- 在浏览器访问127.0.0.1:8088/hello
具体测试步骤见如何创建一个SpringBoot的WebDemo】笔记 方法二使用Spring Initializr创建一个Spring Boot项目 的测试部分
经测试发现,浏览器访问127.0.0.1:8088/hello,成功得到了响应,说明使用yaml配置文件修改端口号配置成功,项目的端口号不再是默认的8080了
思考:如果application.properties和application.yaml中都配置了端口号到底那个生效呢?
测试:两种配置文件都配置端口号,测试到底那个生效
application.properties
server.port=8099
application.yaml
server:
port: 8088
两个配置文件我们都配置端口号后重启项目,浏览器分别访问127.0.0.1:8088/hello
127.0.0.1:8099/hello
结论
发现8099端口可以访问,application.properties优先级是高于application.yaml的
第四步:使用application.yaml配置文件给实体类注入属性值
具体步骤:
- ① 创建实体类Student
- ②在application.yaml中配置Student的属性值
① 创建实体类Student
在org.example.springweb_hello下创建文件夹pojo,在pojo中创建Student类和Pet类
Student类
package org.example.springweb_hello.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;
import java.util.Set;
//使用注解@ConfigurationProperties(prefix = "student"),与yaml文件中student的属性值进行绑定
@ConfigurationProperties(prefix = "student")
@Component//@Component将该类注入到IOC容器中
public class Student {
private String userName;
private Boolean flage;
private Date birth;
private Integer age;
private Pet favoritePet;
private String[