我们在SpringBoot的配置文件pom.xml中可以找到spring-boot-starter-parent这么一个启动器,他是SpringBoot应用的的父级依赖,其中封装了配置文件的过滤规则以及各类依赖。
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的(.yml/.yaml/.properties)。
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/application*.yml</include>
<include>**/application*.yaml</include>
<include>**/application*.properties</include>
</includes>
</resource>
因为SpringBoot已经在底层给配置为默认配置,那么配置文件可以用来修改SpringBoot的默认值,之前配置文件大多都是xml文件,xml文件的配置和yaml文件以及properties文件相比有什么不同。
xml:
<server>
<port>8081</port>
</server>
porperties:(key=value)
server.port = 8081
yaml:(key:空格 value)
server:
port: 8081
yaml文件可以存入list数组或通过(@ConfigurationProperties(prefix = “person”))注解来给实体类及其属性赋值。yaml文件以键值对的形式存入,注意空格位置(存在于上下级之间)。
pet:
- cat
- dog
person:
name: 张三
age: 3
gender: 男
pet:
name: 张三的小狗
age: 3
#person: {name: 张三,age: 1,gerden: 男}
#hobby:
- 1
- 2
- 3
# hobby: [1,2,3]
通过@Component和@ConfigurationProperties组合注解把entity实例化到spring。在test中添加输出测试System.out.println(person);。输出结果为:
配置文件还可以编写占位符生成随机数 ${random.uuid}可以生成uuid:
说明:语法要求严格!
1、空格不能省略
2、以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。
3、属性和值的大小写都是十分敏感的。
JSR303数据校验
也可以通过@Validated注解添加对传输数据的校验,如:@Email可以判断传输数据是否为Email格式,若不是给出默认的提示,提示也可以更改@Email(message = “格式错误!”)。
@Validated
public class Person {
@Email(message = "格式错误!")
private String name;
注:如果@Email报红可以手动添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
**springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件:
优先级1:项目路径下的config文件夹配置文件
优先级2:项目路径下配置文件
优先级3:资源路径下的config文件夹配置文件
优先级4:资源路径下配置文件
优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件;互补配置;**
我们在最低级的配置文件中设置一个项目访问路径的配置来测试互补问题;
_#配置项目的访问路径_server.servlet.context-path=/kuang