yml/yaml: server:
port: 8080
properties::
server.port=8080
配置文件可以修改spring boot 项目的默认配置
yml 的属性和值都是大小写敏感的
---值的写法
1 字面量:普通的值(数字,字符串,布尔)
k:v : 字面直接来写:
字符串默认不用加上单引号或者双引号
值为数组的写法:
使用注解 @ConfigurationProperties 告诉SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定
解决:导入依赖:
将这个类(组件)加入到容器中,使用@Component
@ConfigurationProperties 的功能是由容器提供的,所以必须加上@Component
@ConfigurationProperties是获取配置文件的值,prefix是获取前缀;@Component是将类加入到容器中
注意:yml中 last-name 等价于 lastName
properties 中进行配置:
person.last-name=张三
person.age=18
person.birth=2017/12/15
person.boss=false
#idea properties默认使用的是 utf-8的编码
settings---Encoding 有下面将properties 文件运行时候转换成 ascii勾选上
@ConfigurationProperties 和@Value的区别
以前的时候需要借助bean文件进行配置,为哪个组件(类)创建bean
<bean class="Person">
<property name="lastName" value="?"></property>
</bean> Person是组件(类的名称)
其中name=“lastName” 是属性 value=""是属性的值
bean标签跟@ConfigurationProperties一样的作用都是把Person这个组件(类)加入到容器中
其中value支持的值的写法 :字面量(字符串,数字,Boolean值等类型);
value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL 也就是spring boot的表达式}"
@Value跟之前的bean配置文件是一样的作用,用法也是一样的,如下
@Value("${}/#{1*2}/字面量")
@ConfigurationProperties @Value 以及 bean配置文件的作用都是一样的
@ConfigurationProperties @Value的区别:
语法松散绑定:(last-name lastName)@Value不支持
数据校验:@Validated 表示类中的写入配置文件的属性需要校验;;Configuration支持校验,@Value不支持校验
@Email (表示属性lastEmail 必须是邮箱格式)
private String lastEmail
配置文件yml或者properties 都能获取值
复杂类型封装:向对象,map等类型 需要使用@ConfigurationProperties ,@Value不支持
如果批量获取的话使用@ConfigurationProperties
数据校验的代码:
spring boot 配置文件 yml(yaml) properties
原文:https://www.cnblogs.com/wsnan/p/11868305.html