SpringBoot 配置文件properties 与 yml 从入门到实战实例教程
SpringBoot 的配置机制核心就一句话:代码管逻辑,配置管变数,同一个 jar 包换套配置就能适配不同环境。properties 和 yml 是两种主流的配置文件格式,语法和适用场景不同,但最终都会被 SpringBoot 统一加载并合并生效。
一、配置文件的作用
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 优缺点
优点:
- 可读性高,写法简单,易于理解。
- 支持更多数据类型,可以简单表达对象、数组、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/*转换过程花费精力,配置更复杂时可读性反而更差。
到此这篇关于SpringBoot 配置文件properties 与 yml 从入门到实战实例教程的文章就介绍到这了,更多相关SpringBoot 配置文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Mybatis-Plus接口BaseMapper与Services使用详解
这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-05-05
maven坐标Dependencies和Exclusions的使用
这篇文章主要介绍了maven坐标Dependencies和Exclusions的使用,很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12
Spring Data Elasticsearch 5.x实现单词纠错和自动补全
这篇文章主要为大家介绍了Spring Data Elasticsearch 5.x实现单词纠错和自动补全示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-08-08


最新评论