springBoot-4.配置文件及yml使用

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置文件

作用: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

常用配置
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值