Spring Boot配置文件
Spring Boot配置文件
Spring Boot提供了灵活的配置方式,允许开发者通过配置文件定制应用行为,而无需修改代码。本文将详细介绍Spring Boot的配置文件类型、格式、加载顺序以及最佳实践。
配置文件类型
Spring Boot支持两种主要的配置文件格式:
- properties格式:传统的Java属性文件格式,使用键值对
- YAML格式:结构化配置格式,更易读且支持复杂配置
Properties格式示例
# application.properties
server.port=8080
spring.application.name=my-application
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
YAML格式示例
# application.yml
server:
port: 8080
spring:
application:
name: my-application
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
YAML格式的优势在于它能够更清晰地表示层次结构,减少重复,特别是在复杂配置时。
配置文件位置
Spring Boot会按照以下优先级顺序(从高到低)查找和加载配置文件:
- 命令行参数
SPRING_APPLICATION_JSON
环境变量中的JSONjava:comp/env
中的JNDI属性- Java系统属性(
System.getProperties()
) - 操作系统环境变量
RandomValuePropertySource
随机值属性源- jar包外部的
application-{profile}.properties
或application-{profile}.yml
- jar包内部的
application-{profile}.properties
或application-{profile}.yml
- jar包外部的
application.properties
或application.yml
- jar包内部的
application.properties
或application.yml
@PropertySource
注解引入的属性文件- 默认属性
常见的配置文件位置包括:
- 当前目录的
/config
子目录 - 当前目录
- classpath下的
/config
包 - classpath根目录
配置文件加载顺序
如果在不同位置存在同名配置文件,它们会按照以下顺序合并(后加载的会覆盖先加载的):
file:./config/
:项目根目录下的config目录file:./
:项目根目录classpath:/config/
:classpath下的config目录classpath:/
:classpath根目录
多环境配置(Profile)
Spring Boot支持通过profile为不同环境提供不同的配置:
创建特定环境的配置文件
application-dev.properties
:开发环境application-test.properties
:测试环境application-prod.properties
:生产环境
激活特定Profile
可以通过多种方式激活特定的Profile:
- 配置文件中设置:
# application.properties
spring.profiles.active=dev
- 命令行参数:
java -jar myapp.jar --spring.profiles.active=dev
- 环境变量:
export SPRING_PROFILES_ACTIVE=dev
java -jar myapp.jar
- 编程方式:
SpringApplication app = new SpringApplication(MyApp.class);
app.setAdditionalProfiles("dev");
app.run(args);
在YAML文件中使用多Profile
YAML文件支持在单个文件中定义多个Profile配置,使用---
分隔不同的文档块:
# 默认配置
spring:
application:
name: my-application
server:
port: 8080
---
# 开发环境
spring:
config:
activate:
on-profile: dev
datasource:
url: jdbc:h2:mem:testdb
username: sa
password:
logging:
level:
root: DEBUG
---
# 生产环境
spring:
config:
activate:
on-profile: prod
datasource:
url: jdbc:mysql://prod-server:3306/mydb
username: dbuser
password: dbpass
logging:
level:
root: WARN
配置属性绑定
Spring Boot可以将配置文件中的属性绑定到Java对象中,有多种方式:
使用@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "mail")
public class MailProperties {
private String host;
private int port;
private String username;
private String password;
// getters and setters
}
对应的配置:
mail.host=smtp.example.com
mail.port=25
mail.username=user
mail.password=secret
使用@Value注解
@Component
public class MailService {
@Value("${mail.host}")
private String host;
@Value("${mail.port:25}") // 默认值为25
private int port;
// ...
}
使用Environment对象
@Component
public class MailService {
@Autowired
private Environment env;
public void sendMail() {
String host = env.getProperty("mail.host");
int port = env.getProperty("mail.port", Integer.class, 25);
// ...
}
}
配置属性验证
Spring Boot 2.3.0及以上版本支持对@ConfigurationProperties
绑定的属性进行验证:
@Component
@ConfigurationProperties(prefix = "mail")
@Validated
public class MailProperties {
@NotNull
private String host;
@Min(1)
@Max(65535)
private int port;
@NotEmpty
private String username;
@NotEmpty
private String password;
// getters and setters
}
配置加密
对于敏感配置(如密码、API密钥),可以使用Jasypt等库进行加密:
添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
加密配置
spring.datasource.password=ENC(encrypted_password_here)
jasypt.encryptor.password=your-encryption-password
外部化配置
Spring Boot支持多种方式从外部源加载配置:
命令行参数
java -jar myapp.jar --server.port=8081 --spring.profiles.active=prod
系统属性
java -Dserver.port=8081 -jar myapp.jar
环境变量
export SERVER_PORT=8081
java -jar myapp.jar
Spring Boot会自动将环境变量转换为配置属性:
SERVER_PORT
→server.port
SPRING_DATASOURCE_URL
→spring.datasource.url
外部配置文件
java -jar myapp.jar --spring.config.location=file:///path/to/config/
配置属性列表
Spring Boot提供了大量预定义的配置属性,以下是一些常用类别:
核心属性
# 应用信息
spring.application.name=myapp
spring.profiles.active=dev
# 服务器配置
server.port=8080
server.servlet.context-path=/api
server.compression.enabled=true
数据源配置
# 数据库连接
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接池配置
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect
日志配置
logging.level.root=INFO
logging.level.org.springframework.web=DEBUG
logging.level.com.example=DEBUG
logging.file.name=myapp.log
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
缓存配置
spring.cache.type=redis
spring.redis.host=localhost
spring.redis.port=6379
安全配置
spring.security.user.name=admin
spring.security.user.password=admin
spring.security.user.roles=ADMIN
监控配置
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
自定义配置
除了使用Spring Boot的预定义属性,还可以创建自定义配置:
自定义属性类
@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String apiKey;
private int cacheTimeout;
private Map<String, String> features = new HashMap<>();
private List<String> allowedOrigins = new ArrayList<>();
// getters and setters
}
对应的配置:
app:
api-key: abc123
cache-timeout: 3600
features:
feature1: enabled
feature2: disabled
allowed-origins:
- https://example.com
- https://api.example.com
配置最佳实践
- 使用YAML格式:对于复杂配置,YAML更易读且结构清晰
- 使用多Profile:为不同环境创建专用配置
- 外部化敏感配置:将密码等敏感信息放在外部配置中
- 使用@ConfigurationProperties:对相关配置进行分组
- 提供默认值:为可选配置提供合理的默认值
- 使用松散绑定:配置属性支持多种命名风格(camelCase、kebab-case等)
- 记录配置:使用
@ConfigurationProperties
的@Description
注解或JavaDoc记录配置用途 - 验证配置:使用JSR-303验证确保配置正确
- 避免硬编码:将所有可变配置放在配置文件中
- 使用配置元数据:创建
META-INF/spring-configuration-metadata.json
提供IDE支持
配置故障排查
查看生效的配置
可以通过启用debug日志查看Spring Boot加载的配置:
debug=true
或者通过Actuator端点查看:
management.endpoints.web.exposure.include=env
然后访问/actuator/env
端点。
常见问题
- 配置未生效:检查配置文件位置和命名是否正确
- Profile未激活:确认是否正确设置了
spring.profiles.active
- 属性绑定失败:检查属性名称是否匹配,是否提供了必要的setter方法
- 配置优先级冲突:检查是否有多个位置定义了相同的属性
总结
Spring Boot的配置系统提供了强大而灵活的方式来定制应用行为。通过合理使用配置文件、Profile和属性绑定,可以创建适应不同环境、易于维护的应用程序。
本文介绍了Spring Boot配置文件的类型、位置、加载顺序以及多环境配置等内容,希望能帮助你更好地理解和使用Spring Boot的配置机制。