硬编码让人头疼——环境一换就得改代码。Spring Boot 把数据库连接、端口号这些变数抽到配置文件里,启动时自动加载,省心很多。

Spring Boot 能认三种后缀:.properties、.yml、.yaml。后两者完全等价,只是习惯叫法不同。优先级上,.properties 高于 .yml——如果两个文件里同时写了 server.port,最终生效的是 properties 里的值。所以团队最好统一只用一种格式,免得排查问题时挠头。
Properties 写法与读取
Properties 格式传统,一行一个键值对,= 连接,# 注释。例如:
# 设置项目启动端口
server.port=8080
# 数据库连接配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/testdb
spring.datasource.username=root
用 @Value 配合 ${} 就能取到值:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/prop")
@RestController
public class PropertiesController {
@Value("${spring.datasource.url}")
private String url;
@RequestMapping("/read")
public String readProperties() {
return "从配置文件中读取 url" + url;
}
}
运行结果如下:

但这种写法有个明显的问题——键名越长,重复越多。


















