Spring Boot配置篇:详解application.properties和application.yml
Spring Boot配置篇:详解application.properties和application.yml
在上一篇文章中,我们介绍了如何快速搭建一个Spring Boot应用。在实际开发过程中,配置管理是非常重要的一个环节。Spring Boot提供了多种配置方式,其中最常用的就是application.properties和application.yml文件。本文将详细介绍这两种配置方式的使用方法和最佳实践。
Spring Boot配置文件概述
Spring Boot允许我们通过外部配置来覆盖默认的配置值,使得应用可以在不同的环境中运行而无需修改代码。Spring Boot支持多种外部配置方式,按优先级从高到低排列如下:
- 命令行参数
- SPRING_APPLICATION_JSON中的属性
- ServletConfig初始化参数
- ServletContext初始化参数
- JNDI属性
- Java系统属性
- 操作系统环境变量
- RandomValuePropertySource
- jar包外的application-{profile}.properties
- jar包内的application-{profile}.properties
- jar包外的application.properties
- jar包内的application.properties
其中,application.properties和application.yml是最常用的配置方式。
application.properties详解
application.properties是Java世界中最常见的配置文件格式,采用键值对的形式进行配置。
基本语法
# 基本键值对配置
server.port=8080
spring.application.name=springboot-config-demo# 带有层级关系的配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456# 列表配置
my.list.values=one,two,three# 布尔值配置
my.feature.enabled=true# 数字配置
my.number.value=42
常用配置项
# 服务器配置
server.port=8080
server.servlet.context-path=/api# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect# Redis配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0# 日志配置
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
application.yml详解
YAML(YAML Ain’t Markup Language)是一种简洁的配置文件格式,相比properties文件,YAML更加结构化和易读。
基本语法
server:port: 8080servlet:context-path: /apispring:application:name: springboot-config-demodatasource:url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=falseusername: rootpassword: rootdriver-class-name: com.mysql.cj.jdbc.Driverjpa:hibernate:ddl-auto: updateshow-sql: truedatabase-platform: org.hibernate.dialect.MySQL8Dialectredis:host: localhostport: 6379password: ""database: 0logging:level:root: INFOcom.example: DEBUGpattern:console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"
YAML的高级特性
1. 列表配置
# 行内列表
my:servers: [dev.example.com, test.example.com, prod.example.com]# 多行列表
my:servers:- dev.example.com- test.example.com- prod.example.com
2. 对象配置
# 行内对象
user:info: {name: "张三", age: 25, email: "zhangsan@example.com"}# 多行对象
user:info:name: "张三"age: 25email: "zhangsan@example.com"
3. 多行字符串
# 字面量块标量(保留换行)
message: |这是一个多行字符串每一行都会保留换行符包括最后一行# 折叠块标量(将换行转换为空格)
description: >这也是一个多行字符串但是换行会被转换为空格最终形成一个单行字符串
两种格式对比
| 特性 | application.properties | application.yml | 
|---|---|---|
| 可读性 | 一般 | 优秀 | 
| 层级结构 | 通过点分隔 | 通过缩进表示 | 
| 列表支持 | 需要逗号分隔 | 原生支持 | 
| 多行字符串 | 不支持 | 支持 | 
| 文件大小 | 较大 | 较小 | 
| 学习成本 | 低 | 中等 | 
配置文件的使用
1. 创建配置类
package com.example.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.List;@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {private String name;private int port;private boolean debug;private List servers;// getter和setter方法public String getName() {return name;}public void setName(String name) {this.name = name;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}public boolean isDebug() {return debug;}public void setDebug(boolean debug) {this.debug = debug;}public List getServers() {return servers;}public void setServers(List servers) {this.servers = servers;}
}
2. 在配置文件中添加配置
application.yml:
myapp:name: "我的应用"port: 8080debug: trueservers:- server1.example.com- server2.example.com- server3.example.com
3. 在代码中使用配置
package com.example.controller;import com.example.config.MyAppProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class ConfigController {@Autowiredprivate MyAppProperties myAppProperties;@GetMapping("/config")public String getConfig() {return "应用名称: " + myAppProperties.getName() + ", 端口: " + myAppProperties.getPort() + ", 调试模式: " + myAppProperties.isDebug();}
}
多环境配置
Spring Boot支持通过不同的配置文件来管理不同环境的配置。
1. 创建不同环境的配置文件
- application.properties (默认配置)
- application-dev.properties (开发环境)
- application-test.properties (测试环境)
- application-prod.properties (生产环境)
2. 激活特定环境
通过application.properties激活:
spring.profiles.active=dev
通过命令行参数激活:
java -jar app.jar --spring.profiles.active=prod
3. 环境配置示例
application-dev.properties:
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/dev_db
spring.datasource.username=dev_user
spring.datasource.password=dev_password
logging.level.root=DEBUG
application-prod.properties:
server.port=80
spring.datasource.url=jdbc:mysql://prod-server:3306/prod_db
spring.datasource.username=prod_user
spring.datasource.password=prod_password
logging.level.root=WARN
配置文件最佳实践
1. 配置文件组织原则
# 按功能模块组织配置
server:port: 8080servlet:context-path: /apispring:datasource:# 数据库相关配置redis:# Redis相关配置jpa:# JPA相关配置logging:# 日志相关配置myapp:# 自定义应用配置
2. 敏感信息处理
不要在配置文件中直接存储敏感信息,可以使用环境变量:
spring:datasource:username: ${DB_USERNAME:root}password: ${DB_PASSWORD:password}
3. 配置验证
package com.example.config;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Positive;@Component
@Validated
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {@NotEmptyprivate String name;@Positiveprivate int port = 8080;// getter和setter方法
}
总结
在本文中,我们详细介绍了Spring Boot中两种主要的配置文件格式:application.properties和application.yml。我们学习了:
- 两种配置文件的基本语法和使用方法
- YAML格式的高级特性,如列表、对象和多行字符串
- 两种格式的对比和选择建议
- 如何创建和使用自定义配置类
- 多环境配置的管理方式
- 配置文件的最佳实践
合理使用配置文件可以让我们的Spring Boot应用更加灵活和易于维护。在下一篇文章中,我们将介绍如何在Spring Boot中整合MyBatis进行数据访问操作。
作者:CSDN博客助手
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。
