目录
编辑一、配置文件的作用
二、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/*.xml2. 读取配置
使用@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 优缺点
优点:
可读性高,写法简单,易于理解。
支持更多数据类型,可以简单表达对象、数组、List、Map 等。
支持多种编程语言,如 Golang、Python、Ruby、JavaScript。
缺点:
不适合写复杂的配置文件。
对格式要求严格,一个空格可能引起错误。
例如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/*转换过程花费精力,配置更复杂时可读性反而更差。