什么是配置文件?
类比手机的设置界面
- 大部分软件都需要用户自定义设置功能,比如字体大小、主题颜色。
- 如果在代码中写死这些值(硬编码),所有用户设备上的值都是一样的,不够灵活。
- 配置文件的作用:将这些可能变化的设置集中在外部文件里,程序启动时自动读取配置的数值。
Spring Boot 支持的配置文件格式
1. application.properties
(旧版)
特点:简单键值对,类似外卖菜单
# 设置服务端口号(类似手机设置中的音量)
server.port=8080# 数据库连接配置(类似保存 WiFi 密码)
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
优点:语法简单,适合固定配置
缺点:配置项多时会有重复前缀(如 spring.datasource.xxx
)。
2. application.yml
/ application.yaml
(新版)
特点:树状结构,类似文件夹层级
# 类似结构化的手机设置菜单
server:port: 8080 # 端口号spring:datasource: # 数据库配置(类似“网络设置”大分类)url: jdbc:mysql://localhost:3306/mydbusername: rootpassword: 123456student:id: 1001name: 小明
优点:层次清晰,无重复前缀
缺点:严格缩进(类似 Python),填错缩进程序报错。
如何读取配置?
通过 @Value
读取单个值(简单方便)
@Value("${server.port}") // 读取配置中的端口号
private int port;@RequestMapping("/showPort")
public String showPort() {return "当前服务端口是:" + port;
}
通过 @ConfigurationProperties
读取对象(适合复杂配置)
# 配置学生信息(类似用户个人信息)
student:id: 1001name: 小明
@Data
@Component
@ConfigurationProperties(prefix = "student") // 绑定前缀
public class Student {private int id;private String name;
}@RestController
public class StudentController {@Autowiredprivate Student student;@RequestMapping("/studentInfo")public String getInfo() {return "学生ID:" + student.getId() + ",姓名:" + student.getName();}
}
为什么需要两种配置格式?
- 迁移成本:早期项目用
.properties
,新项目更推荐.yml
。 - 团队习惯:YAML 格式层次清晰,但在复杂配置中可能不如 Properties 直观。
示例:验证码配置
配置文件中定义参数
# 验证码参数配置(像素宽高、Session 存储的 Key)
captcha:width: 200height: 100session:key: CAPTCHA_CODE
Java 代码读取配置
@Data
@Component
@ConfigurationProperties(prefix = "captcha")
public class CaptchaConfig {private int width;private int height;private Session session;@Datapublic static class Session {private String key;}
}@RestController
public class CaptchaController {@Autowiredprivate CaptchaConfig config;@Autowiredprivate HttpSession session;@GetMapping("/captcha")public void generateCaptcha() {// 用 Hutool 生成验证码图片,存入 SessionLineCaptcha captcha = CaptchaUtil.createLineCaptcha(config.getWidth(), config.getHeight());session.setAttribute(config.getSession().getKey(), captcha.getCode());captcha.write(response.getOutputStream()); // 返回图片给前端}
}
总结
- 用途:
properties
和yml
都是为了让程序更灵活,不用改代码就能调整参数。 - 对比:
properties
:类似简单列表,适合少量配置。yml
:类似树状菜单,适合多层结构。
- 选择建议:新项目统一用
.yml
,旧项目按习惯维护。