当前位置: 代码网 > it编程>编程语言>Java > SpringBoot 配置文件properties 与 yml 从入门到实战实例教程

SpringBoot 配置文件properties 与 yml 从入门到实战实例教程

2026年10月01日 • Java •我要评论
springboot 的配置机制核心就一句话:‌代码管逻辑,配置管变数,同一个 jar 包换套配置就能适配不同环境‌。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 优缺点

优点:

  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/*

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

到此这篇关于springboot 配置文件properties 与 yml 从入门到实战实例教程的文章就介绍到这了,更多相关springboot 配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

赞 (0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com