SpringBoot配置文件详解!
创作时间:
作者:
@小白创作中心
SpringBoot配置文件详解!
引用
CSDN
1.
https://blog.csdn.net/qq_56158663/article/details/146235023
一、什么是 Spring Boot 配置文件?
你可以把 Spring Boot 配置文件想象成一个“设置说明书”,告诉 Spring Boot 程序:
- “嘿,数据库的地址是这个,用户名是这个,密码是这个!”
- “嘿,端口号用 8080,别用默认的!”
- “嘿,这个功能要开启,那个功能要关闭!”
简单来说,配置文件就是用来配置你的 Spring Boot 程序的各种参数的。这样做的好处是,你不用把这些参数硬编码到代码里,方便修改和维护。 比如,你想换个数据库,直接改配置文件就行,不用改代码重新编译。
两种常见的配置文件格式:properties 和 yml
Spring Boot 主要支持两种格式的配置文件:
- properties 文件:
- 格式:键值对,用等号分隔。
- 例子:
server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=123456 - 特点:简单直接,容易理解,但层级结构不明显。
- 注意事项:
- 转义字符:如果值中包含特殊字符,比如冒号或等号, 需要使用反斜杠进行转义。 例如:
my.value=This is a\: test - 注释:使用
#开头表示注释。 - 编码:建议使用 UTF-8 编码,避免中文乱码问题。
- 重复的 key:如果出现重复的 key,后面的值会覆盖前面的值。
- yml 文件 (或 yaml 文件):
- 格式:使用缩进表示层级关系。
- 例子:
server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: 123456 - 特点:结构清晰,可读性好,适合配置复杂的参数。
- 注意事项:
- 缩进:缩进非常重要! 必须使用空格进行缩进,不能使用 Tab 键。 建议使用 2 个空格作为一级缩进。
- 大小写敏感:key 是大小写敏感的。
- 注释:使用
#开头表示注释。 - 字符串:字符串可以不用引号,但如果包含特殊字符或空格,建议使用单引号或双引号括起来。
- 布尔值:可以使用
true或false(不区分大小写),也可以使用yes或no。 - 空值:可以使用
null或~表示空值。 - 数组:可以使用
-开头表示数组的元素。
总结一下:
- properties 像是一张简单的表格,每一行都是一个配置项。
- yml 像是一棵树,用缩进来表示配置项之间的关系。
Spring Boot 默认的配置文件名:
Spring Boot 默认会加载以下文件(按优先级从低到高):
application.properties或application.yml:位于src/main/resources目录下。application-{profile}.properties或application-{profile}.yml:位于src/main/resources目录下,{profile}是环境名称,比如dev(开发环境),prod(生产环境)。 你可以通过设置spring.profiles.active来激活不同的环境配置文件。
二、如何从配置文件中获取值?
Spring Boot 提供了几种方式来获取配置文件的值:
- 使用
@Value注解:
- 场景:直接将配置值注入到类的字段中。
- 例子:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyConfig { @Value("${server.port}") // 从配置文件中读取 server.port 的值 private int serverPort; @Value("${spring.datasource.url}") private String datasourceUrl; public int getServerPort() { return serverPort; } public String getDatasourceUrl() { return datasourceUrl; } } - 解释:
@Value("${...}"):告诉 Spring 从配置文件中读取指定 key 的值。serverPort和datasourceUrl字段会自动被赋值。${...}里面的内容就是配置项的 key,比如server.port。
- 使用
@ConfigurationProperties注解:
- 场景:将一组相关的配置项绑定到一个 Java Bean 中。
- 例子:
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "my.app") // 指定配置项的前缀 public class MyAppConfig { private String name; private String version; private String author; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = this.author; } }my: app: name: My Awesome App version: 1.0 author: John Doe - 解释:
@ConfigurationProperties(prefix = "my.app"):告诉 Spring 将所有以my.app开头的配置项绑定到这个 Bean 中。name,version,author字段会自动被赋值。- 注意:这个 Bean 必须要有 setter 方法,Spring 才能给字段赋值。
- 使用
Environment对象:
- 场景:动态获取配置值,或者获取一些系统环境变量。
- 例子:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class MyService { @Autowired private Environment environment; public String getDatabaseUrl() { return environment.getProperty("spring.datasource.url"); } } - 解释:
@Autowired private Environment environment;:注入Environment对象。environment.getProperty("spring.datasource.url"):从环境中获取spring.datasource.url的值。
三、如何从自定义配置文件中取值?
有时候,你可能需要使用自己的配置文件,而不是 application.properties 或 application.yml。 比如,你想把一些敏感信息放在一个单独的文件里。
- 指定配置文件的位置:
- 方式一:在
application.properties或application.yml中指定:spring.config.location=classpath:my-config.properties,file:/path/to/my-config.ymlspring: config: location: classpath:my-config.properties,file:/path/to/my-config.yml - 解释:
spring.config.location:指定配置文件的位置。classpath::表示从 classpath 中加载。file::表示从文件系统中加载。- 多个配置文件用逗号分隔。
- 方式二:使用命令行参数:
java -jar myapp.jar --spring.config.location=classpath:my-config.properties,file:/path/to/my-config.yml
- 从自定义配置文件中取值:
- 使用
@Value、@ConfigurationProperties或Environment对象,和从application.properties或application.yml中取值的方式一样。 Spring Boot 会自动加载你指定的配置文件,并将里面的配置项添加到环境中。
举个完整的例子:
创建自定义配置文件
my-config.properties:my.custom.message=Hello from my custom config!在
application.properties中指定自定义配置文件的位置:spring.config.location=classpath:my-config.properties在 Java 代码中获取自定义配置文件的值:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class MyService { @Value("${my.custom.message}") private String customMessage; public String getCustomMessage() { return customMessage; } }import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyRunner implements CommandLineRunner { @Autowired private MyService myService; @Override public void run(String... args) throws Exception { System.out.println(myService.getCustomMessage()); // 输出:Hello from my custom config! } }
四、总结:
- 配置文件是 Spring Boot 程序的重要组成部分,用于配置各种参数。
properties和yml是两种常见的配置文件格式,yml更加结构化。- 可以使用
@Value、@ConfigurationProperties或Environment对象从配置文件中获取值。 - 可以通过
spring.config.location指定自定义配置文件的位置。
希望这篇文章能够帮助你理解 Spring Boot 中的配置文件! 记住,多写代码,多实践,才能真正掌握这些知识。 加油!
热门推荐
压强差在化学实验中的应用
国画调色技法详解:颜料种类、调色方法与注意事项
如何提升智能智慧制造的生产效率?
三国志幻想大陆2李儒技能强度解析:中毒机制详解
探索元宇宙公司的商业模式与未来趋势
谁说跑步很烧钱?这样算,其实省了一大笔
旅游景区的营销策略有哪些创新方法?
取名字有什么要注意的
IP地址选静态好还是DHCP好:深入解析与选择指南
方阵:结构、演习、营地
4000元组装电脑攻略:关键硬件搭配详解与推荐
2025考研调剂意向采集系统怎么用?提前锁定院校的隐藏技巧(全日制、非全)
小窍门:如何挑选高品质的开关插座面板?
500度近视什么概念
传统邂逅创新、灯火点亮团圆 雨花台区元宵主题活动演绎古今文化交响
花卉施肥全攻略:从羊粪到化学肥的使用指南
跳绳的全方位健康益处:心肺功能提升、减脂塑形与情绪改善
英语被动语态的八种基本结构
英语被动语态的八种基本结构
Rh血型系统:定义、临床意义及检查项目详解
食管炎的症状有哪些表现
食管炎忌口食物一览
垂丝海棠和樱花的区别 慧眼识花只需要这么简单的几步
小心!驱蚊器频频惹“火” 这些注意事项要牢记
古朝权力的守护者:九门提督官职解析
运用「对比原则」打破单调呆板的设计
鲁班锁:从传统智力玩具到现代工艺美学
团队协作的启发事例有哪些
世界各国人均每天蛋白质,蔬菜和水果的摄入量排名!
掌握PPT布局设计的10大基本原则,提升演示效果