Spring Boot application.properties 配置文件详解

Spring Boot application.properties 配置文件详解

一、概述

application.properties 是 Spring Boot 默认的配置文件,位于 src/main/resources 目录下。Spring Boot 启动时会自动加载该文件中的所有配置项,将其解析为键值对,供应用通过 @Value@ConfigurationPropertiesEnvironment 对象使用。

application.propertiesapplication.yml 的区别在于格式:properties 是扁平的键值对格式,yml 是树形层级格式。两者可以共存,properties 的优先级更高(当同一个配置项同时出现在两个文件中时,properties 中的值生效)。

二、基本语法

2.1 键值对格式

properties 复制代码
server.port=8080
app.name=my-application
app.timeout=30

键和值之间用 =: 分隔,建议使用 =。值不需要加引号。

2.2 层级表示

使用 . 表示层级关系:

properties 复制代码
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

2.3 注释

使用 # 添加注释:

properties 复制代码
# 服务器端口配置
server.port=8080

# 应用名称
spring.application.name=myapp

三、常用配置示例

3.1 Web 服务器配置

properties 复制代码
# 端口
server.port=8080

# 上下文路径
server.servlet.context-path=/api

# 编码
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true

3.2 数据源配置

properties 复制代码
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 连接池配置(HikariCP)
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.connection-timeout=30000

3.3 日志配置

properties 复制代码
# 日志级别
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.level.org.springframework.web=DEBUG

# 日志文件
logging.file.name=logs/myapp.log
logging.logback.rollingpolicy.max-history=7
logging.logback.rollingpolicy.total-size-cap=10GB

# 日志格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n

3.4 MyBatis 配置

properties 复制代码
# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.entity
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.cache-enabled=true

3.5 多环境配置

在同一个 properties 文件中无法像 yml 那样使用 --- 分隔多文档块,需要通过多个配置文件实现。

创建不同的配置文件:

  • application.properties:默认配置
  • application-dev.properties:开发环境
  • application-prod.properties:生产环境
properties 复制代码
# application.properties
spring.profiles.active=dev
properties 复制代码
# application-dev.properties
server.port=8080
logging.level.root=DEBUG
properties 复制代码
# application-prod.properties
server.port=80
logging.level.root=WARN

3.6 Jackson JSON 配置

properties 复制代码
# 日期格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Shanghai

# 序列化配置
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.serialization.indent-output=true

# 忽略未知字段
spring.jackson.deserialization.fail-on-unknown-properties=false

四、占位符与默认值

4.1 引用其他配置项

properties 复制代码
app.name=myapp
app.description=${app.name} is a Spring Boot application

4.2 设置默认值

properties 复制代码
# 如果没有配置 app.timeout,使用默认值 30
app.timeout=${app.timeout:30}
java 复制代码
@Value("${app.timeout:30}")
private int timeout;

4.3 随机值生成

properties 复制代码
app.secret=${random.value}
app.uuid=${random.uuid}
app.number=${random.int(100)}
app.range=${random.int(10,20)}
app.long=${random.long}

五、与 @ConfigurationProperties 绑定

5.1 前缀绑定

properties 复制代码
app.name=myapp
app.timeout=30
app.servers=server1,server2,server3
app.features.cache=true
app.features.logging=false
app.security.secret=secret123
app.security.enabled=true
java 复制代码
@Component
@ConfigurationProperties(prefix = "app")
@Data
public class AppProperties {
    private String name;
    private int timeout = 30;  // 默认值
    private List<String> servers;
    private Map<String, Boolean> features = new HashMap<>();
    private Security security = new Security();
    
    @Data
    public static class Security {
        private boolean enabled;
        private String secret;
    }
}

5.2 数组与集合

properties 复制代码
# 数组
app.servers[0]=server1
app.servers[1]=server2
app.servers[2]=server3

# 或者使用逗号分隔
app.servers=server1,server2,server3

六、int 与 String 类型的区别

6.1 String 类型

properties 复制代码
# 直接写字符串值,不需要引号
app.name=myapp
app.description=This is my app

6.2 int / Integer 类型

properties 复制代码
# 直接写数字
app.timeout=30
app.max-size=1024

如果配置的值不是数字,注入 Integer 类型时会抛出 NumberFormatException

6.3 布尔类型

properties 复制代码
# 支持 true/false、on/off、yes/no、1/0
app.cache-enabled=true
app.debug-mode=false

6.4 类型转换验证

启动时如果配置类型错误,Spring Boot 会报错并提示正确格式。例如给 Integer 注入 abc 会输出:

python 复制代码
Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'app.timeout'

七、配置优先级

application.properties 中的配置会被高优先级的配置覆盖:

bash 复制代码
# 1. 命令行参数(最高)
java -jar myapp.jar --server.port=8081

# 2. 环境变量
export SERVER_PORT=8081

# 3. JVM 系统属性
java -Dserver.port=8081 -jar myapp.jar

# 4. 外部配置文件(config/ 目录下)
/opt/app/config/application.properties

# 5. 内部配置文件(classpath 根目录)
src/main/resources/application.properties

八、扩展配置

8.1 自定义配置文件

java 复制代码
@Configuration
@PropertySource("classpath:custom.properties")
public class CustomConfig {
    @Value("${custom.value}")
    private String value;
}

8.2 添加多个配置源

java 复制代码
@Configuration
@PropertySources({
    @PropertySource("classpath:common.properties"),
    @PropertySource("file:/opt/config/override.properties")
})
public class MultiSourceConfig {
}

8.3 在测试中覆盖

java 复制代码
@SpringBootTest
@TestPropertySource(properties = {
    "app.name=test-app",
    "app.timeout=5000"
})
public class ConfigTest {
}

九、最佳实践

  • 使用 Profile 管理多环境配置,将不同环境的差异配置放在 application-{profile}.properties
  • 敏感信息(数据库密码、API Key)通过环境变量注入,不要写在配置文件中
  • 复杂配置使用 @ConfigurationProperties 绑定到对象,而不是用 @Value 逐个注入
  • 为自定义配置添加 spring-boot-configuration-processor 依赖,生成配置元数据,获得 IDE 提示
  • 配置项命名使用小写字母和 . 分隔,spring.datasource.urlmybatis.mapper-locations
  • 使用默认值或必要的校验注解,保证应用在配置缺失时仍能正常启动
  • 生产环境通过 --spring.config.location 指定外部配置文件,保证配置的可维护性

十、与 YAML 的对比

维度 properties yml
格式 扁平键值对,重复前缀较多 树形层级,结构清晰
多文档支持 需要多个文件 支持 --- 分隔多文档块
列表表示 索引或逗号分隔 使用 - 列表项
适用场景 简单配置、传统项目 复杂层级配置、现代项目
Spring Boot 支持 ✅ 默认支持 ✅ 默认支持

两种格式可以共存,properties 优先级更高。如果不确定用哪种,推荐使用 yml,因为结构更清晰,尤其在配置项较多时。如果团队习惯了 properties 格式,或项目有其他工具依赖 properties 格式,继续使用 properties 也是合理的。

相关推荐
分支预测失败15 分钟前
RISC-V 虚拟内存与 MMU 实战:从 Sv39 页表到 Linux 地址空间
后端
步行cgn16 分钟前
@SpringBootTest 详解:Spring Boot 测试的核心注解
后端
对象存储与RustFS21 分钟前
给 RustFS 拆多租户权限:IAM 用户、组与策略的实战
后端·rust·开源
ZGG0031 小时前
MCP 02:MCP 的各类比对——和 Function Calling、A2A、Skill 到底什么关系
人工智能·后端·python
IT_陈寒1 小时前
Vite热更新突然失效?可能是这个配置在捣鬼
前端·人工智能·后端
SelectDB技术团队2 小时前
统一全文检索与 SQL 分析:Apache Doris 日志分析实践
大数据·数据结构·后端·python·全文检索·doris·日志分析
霸道流氓气质2 小时前
Spring AI多模型路由与动态切换
java·后端·spring
艺杯羹2 小时前
全栈信创落地实录:基于银河麒麟V10与达梦数据库DM8的SpringBoot工业级适配指南
java·数据库·spring boot·后端·spring
学长毕业设计10 小时前
基于SpringBoot的公益基金管理系统(源码+文档+讲解视频)
java·spring boot·后端