news 2026/9/30 2:35:40

SpringBoot 配置文件详解:properties 与 yml 从入门到实战

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot 配置文件详解:properties 与 yml 从入门到实战

目录

​编辑一、配置文件的作用

二、SpringBoot 配置文件格式

1. 快速修改端口

2. properties 与 yml 共存

三、properties 配置文件

1. 基本语法 连接:

2. 读取配置

3. 缺点

四、yml 配置文件

1. 基本语法

2. 配置不同数据类型及 null

3. 读取 yml 配置

4. 单双引号的区别

5. 配置对象

6. 配置集合 List

7. 配置 Map

8. yml 优缺点


一、配置文件的作用

Spring Boot 中的配置文件常用于:

  • 项目启动端口

  • 数据库连接信息(URL、用户名、密码)

  • 第三方系统调用密钥

  • 日志级别、异常日志等

Spring Boot 内置 Tomcat,默认端口是8080。如果端口被占用,就可以通过配置文件修改。

二、SpringBoot 配置文件格式

Spring Boot 支持三种配置文件:

  • application.properites

  • application.yml

  • application.yaml

其中 yml是 yaml的简写,实际开发中使用频率最高。yaml和 yml用法一样,课堂中通常只讲 yml。

项目启动时,Spring Boot 会自动从 classpath 路径加载 application.properites 或 application.yml / application.yaml。

1. 快速修改端口

创建 Spring Boot 项目后,resources目录下默认会生成application.properties。修改端口:

server.port=9090

运行后,日志中打印:

Tomcat initialized with port(s): 9090 (http) Tomcat started on port(s): 9090 (http)

此时访问http://127.0.0.1:9090/login.html即可,原来的8080端口不再生效。


2. properties 与 yml 共存

理论上,properties 和 .yml 可以同时存在同一个项目中,两个配置都会加载,如果内容冲突,以 properties 为主,所以 properties 优先级更高

但实际业务中,通常统一使用一种格式,便于维护,降低故障率。


三、properties 配置文件

properties是最早期的配置文件格式,也是创建 Spring Boot 项目时的默认格式。

1. 基本语法连接:

以键值对形式配置,key 和 value 之间使用 = 连接:

## MySql ## #驱动类名称 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #数据库连接的url spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lottery_system?characterEncoding=utf8&useSSL=false #连接数据库的⽤⼾名 spring.datasource.username=root #连接数据库的密码 spring.datasource.password=123456 ## MyBatis ## #配置mybatis xml的⽂件路径,在 resources/mapper 创建所有表的 xml ⽂件 #mybatis.mapper-locations=classpath:mapper/*Mapper.xml #配置驼峰⾃动转换 mybatis-plus.configuration.map-underscore-to-camel-case=true mybatis-plus.type-handlers-package=com.example.lotterysystem.dao.handler mybatis-plus.mapper-locations=classpath:mapper/*.xml

2. 读取配置

使用@Value注解读取,格式为 ${key}:

import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PropertiesController { @Value("${mykey.key1}") private String key1; @RequestMapping("/key") public String key() { return "读取到值:" + key1; } }

访问 hhtp://127.0.0.1:8080/key,页面显示读取到的值。

3. 缺点

properties存在大量冗余信息,例如:

## MySql ## #驱动类名称 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #数据库连接的url spring.datasource.url=jdbc:mysql://127.0.0.1:3306/lottery_system?characterEncoding=utf8&useSSL=false #连接数据库的⽤⼾名 spring.datasource.username=root #连接数据库的密码 spring.datasource.password=123456

每个配置都要重复写spring.datasource,层级关系不直观。而yml可以很好地解决这个问题。

四、yml 配置文件

yml是 YAML(Yet Another Markup Language)的缩写,采用树形结构,可读性更高。

1. 基本语法

基础语法是key: value,注意:

  • 冒号后面必须有空格

  • 空格不可省略

  • 层级之间用换行和缩进表示

正确示例:

key1: java

错误示例:

key2:java # 冒号后没有空格,错误

使用yml连接数据库:

spring: datasource: url: jdbc:mysql://127.0.0.1:3306/dbname?characterEncoding=utf8&useSSL=false username: root password: root

对比properties,yml消除了冗余,层级清晰。

2. 配置不同数据类型及 null

# 字符串 string.value: Hello # 布尔值 boolean.value: true boolean.value1: false # 整数 int.value: 10 # 浮点数 float.value: 3.14159 # Null,~ 代表 null null.value: ~ # 空字符串,直接后面什么都不加,或使用引号 empty.value: ''

3. 读取 yml 配置

读取方式与properties相同,使用@Value:

@RestController public class ReadYml { @Value("${string.hello}") private String hello; @RequestMapping("/ymlKey") public String key() { return "读取到值:" + hello; } }

4. 单双引号的区别

字符串默认不用加引号。如果加单引号或双引号,表示特殊含义:

string: str1: Hello \n Spring Boot. str2: 'Hello \n Spring Boot.' str3: "Hello \n Spring Boot."

读取代码:

@Value("${string.str1}") private String str1; @Value("${string.str2}") private String str2; @Value("${string.str3}") private String str3; @RequestMapping("/yml") public String readYml() { System.out.println(str1); System.out.println(str2); System.out.println(str3); return "yml"; }

输出结果:

Hello \n Spring Boot. Hello \n Spring Boot. Hello Spring Boot.

结论:

  • 字符串默认不加引号。

  • 单引号会转义特殊字符,\n不再表示换行,而是普通字符串。

  • 双引号不会转义特殊字符,\n表示换行。

5. 配置对象

student: id: 1 name: Java age: 18

行内写法:

student: {id: 1, name: Java, age: 18}

读取对象不能使用@Value,而要用@ConfigurationProperties:

import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @ConfigurationProperties(prefix = "student") @Component @Data public class Student { private int id; private String name; private int age; }

调用:

@RestController public class StudentController { @Autowired private Student student; @RequestMapping("/readStudent") public String readStudent() { return student.toString(); } }

6. 配置集合 List

dbtypes: name: - mysql - sqlserver - db2

读取:

@Component @ConfigurationProperties("dbtypes") @Data public class ListConfig { private List<String> name; }
@RestController public class ReadYml2 { @Autowired private ListConfig listConfig; @RequestMapping("/readList") public String readList() { return listConfig.toString(); } }

7. 配置 Map

maptypes: map: k1: kk1 k2: kk2 k3: kk3

行内写法:

maptypes: {map: {k1: kk1, k2: kk2, k3: kk3}}

读取:

@Component @ConfigurationProperties("maptypes") @Data public class MapConfig { private HashMap<String, String> map; }
@RestController public class ReadYml2 { @Autowired private MapConfig mapConfig; @RequestMapping("/readMap") public String readStudent() { return mapConfig.toString(); } }

8. yml 优缺点

优点:

  1. 可读性高,写法简单,易于理解。

  2. 支持更多数据类型,可以简单表达对象、数组、List、Map 等。

  3. 支持多种编程语言,如 Golang、Python、Ruby、JavaScript。

缺点:

  1. 不适合写复杂的配置文件。

  2. 对格式要求严格,一个空格可能引起错误。

例如properties中的复杂配置:

keycloak.realm=demo keycloak.resource=fm-cache-cloud keycloak.credentials.secret=d4589683-0ce7-4982-bcd3 keycloak.security[0].authRoles[0]=user keycloak.security[0].collections[0].name=ssologinurl keycloak.security[0].collections[0].patterns[0]=/login/*

转换为yml:

keycloak: realm: demo resource: fm-cache-cloud credentials: secret: d4589683-0ce7-4982-bcd3 security: - authRoles: - user collections: - name: ssologinurl patterns: - /login/*

转换过程花费精力,配置更复杂时可读性反而更差。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/9/30 2:35:22

MCP 安全接入工具实战:Java 后端权限、审计与风险控制配置指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/30 2:35:11

Claude Code 自用高效插件:把 settings 改到 TaoToken 打通 HUD 与 Mermaid

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

作者头像 李华
网站建设 2026/9/30 2:34:39

深入理解 DAG Agent:用有向无环图编排智能体的并行任务流

文档教程知识库 【免费下载链接】developer-roadmap Interactive roadmaps, guides and other educational content to help developers grow in their careers. 项目地址&#xff1a; https://gitcode.com/GitHub_Trending/de/developer-roadmap 点击查看 免费下载 本文基于 …

作者头像 李华
网站建设 2026/9/30 2:34:10

Qt 新手必学核心语法(基于 C++,逐句讲解,保姆级)

前置记住&#xff1a;Qt 是C 框架&#xff0c;下面这些是 Qt 额外增加的宏 / 关键字&#xff0c;不是标准 C&#xff0c;靠 moc&#xff08;元对象编译器&#xff09;处理。普通 C 语法&#xff08;if、for、class、指针、vector 等&#xff09;照常使用。 环境&#xff1a;Qt …

作者头像 李华