配置文件
作用:spring boot 的自动配置,可以使用配置文件 对默认配置进行修改
默认配置文件:
1.application.properties:key=value ,或者 行内写法( [set / list / 数组],{map / 对象类型的属性}),[]可省略,{}不可省略
2.application.yml:key=[空格]value,通过垂直对齐指定层级关系
3.xml
通过配置文件给对象注入值
1.注入值,数据可以来自 application.properties 或 application.yaml
student:
name: 哈哈
age: 22
sex: true
birthday: 2019/03/22
2.绑定,在类名前加标注
@Component
@ConfigurationProperties(prefix=“student”)
2.1 通过@Value(“ele”)绑定,在类的属性上加标注
2.2 @ConfigurationProperties 与 @Value 差异
@ConfigurationProperties和 @Value 注入是互补的,ConfigurationProperties优先级高
| @ConfigurationProperties | @Value | |
|---|---|---|
| 注入方式 | 批量注入 | 单个注入 |
| 支持松散写法 | 是 | 否 |
| 支持SpringEL | 否 | 是 |
| 支持JSR303数据校验 | 是 | 否 |
| 支持注入复杂类型 | 是 | 否 |
简单类型:8个基础类型 + String + Date ,除了简单类型就是复杂类型
总结
1.优先级:properties > yml > @Value
2.SpringEL只适用于@Value,其他适用于ConfigurationProperties
3.application.properties 和 application.yml 可以存在于以下四个文件,优先级从上而下
file: 根目录/config
file: 根目录
classpath: 根目录/config
classpath: 根目录
@PropertySource
程序默认加载application.Properties 和 application.yml 中的数据,
可以使用@PropertySource(value={“classpath:xxx.properties”}) 加载xxx.properties文件中的数据
但是@PropertySource只能指定加载 .properties的文件,不能加载 .yml
@ImportResource
让spring boot 识别默认配置之外的自定义文件配置;
如需要加载xxx.xml的文件配置,则在主配置类前使用 @ImportResource(locations={“classpath:xxx.xml”})
spring boot推荐使用注解配置类,而不是xml文件配置

@全局占位符
1.随机数

2.引用变量值
如 yml中 配置 name: ${student.name},
实际读取的是properties中的student.name配置
other
常用配置

本文深入解析SpringBoot配置机制,涵盖properties与yml配置文件的区别,@Value与@ConfigurationProperties的使用场景对比,以及如何加载自定义配置文件。了解优先级、数据注入与校验,掌握配置文件的多层次加载路径。
1023

被折叠的 条评论
为什么被折叠?



