Spring Boot配置
Spring Boot配置[编辑 | 编辑源代码]
介绍[编辑 | 编辑源代码]
Spring Boot配置是Spring Boot应用程序的核心部分,它允许开发者通过多种方式定义和管理应用程序的行为,而无需编写大量样板代码。Spring Boot提供了灵活的配置机制,包括:
- 默认约定优于配置(Convention over Configuration)
- 外部化配置(如`application.properties`或`application.yml`)
- 环境变量和命令行参数
- 条件化配置(如`@Conditional`注解)
Spring Boot的配置系统基于Spring Framework的`Environment`和`PropertySource`抽象,支持多环境配置(如开发、测试、生产环境),并允许开发者轻松覆盖默认值。
配置方式[编辑 | 编辑源代码]
1. 默认配置[编辑 | 编辑源代码]
Spring Boot通过自动配置(Auto-configuration)为常见场景提供默认值。例如,内嵌的Tomcat服务器默认监听8080端口。
2. 外部化配置[编辑 | 编辑源代码]
开发者可以通过以下文件定义配置:
- `application.properties`(键值对格式)
- `application.yml`(YAML格式,支持层级结构)
示例:`application.properties`[编辑 | 编辑源代码]
# 配置服务器端口
server.port=9090
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
示例:`application.yml`[编辑 | 编辑源代码]
server:
port: 9090
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: secret
3. 环境变量和命令行参数[编辑 | 编辑源代码]
Spring Boot支持通过环境变量或命令行参数覆盖配置。例如:
- 命令行:`java -jar app.jar --server.port=9090`
- 环境变量:`export SERVER_PORT=9090`
4. 条件化配置[编辑 | 编辑源代码]
使用`@Conditional`注解可以根据条件动态加载配置。例如:
@Configuration
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureConfig {
// 仅当feature.enabled=true时加载此配置
}
多环境配置[编辑 | 编辑源代码]
Spring Boot支持通过`spring.profiles.active`指定激活的配置文件。例如:
- 创建`application-dev.properties`和`application-prod.properties`
- 激活开发环境:`spring.profiles.active=dev`
示例:多环境YAML配置[编辑 | 编辑源代码]
# application.yml(默认配置)
server:
port: 8080
---
# 开发环境配置
spring:
profiles: dev
server:
port: 9090
---
# 生产环境配置
spring:
profiles: prod
server:
port: 80
配置优先级[编辑 | 编辑源代码]
Spring Boot配置的优先级从高到低如下: 1. 命令行参数 2. 环境变量 3. `application-{profile}.properties`或`application-{profile}.yml` 4. `application.properties`或`application.yml` 5. 默认配置
实际案例[编辑 | 编辑源代码]
案例1:动态数据库配置[编辑 | 编辑源代码]
通过`application-prod.yml`配置生产环境数据库:
spring:
profiles: prod
datasource:
url: jdbc:mysql://prod-db:3306/mydb
username: admin
password: ${DB_PASSWORD} # 从环境变量注入
案例2:自定义配置属性[编辑 | 编辑源代码]
定义自定义属性并注入到Bean中:
// application.yml
app:
welcome-message: "Hello, Spring Boot!"
// 配置类
@Configuration
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String welcomeMessage;
// Getter和Setter
}
// 使用配置
@RestController
public class WelcomeController {
@Autowired
private AppConfig appConfig;
@GetMapping("/welcome")
public String welcome() {
return appConfig.getWelcomeMessage();
}
}
高级主题[编辑 | 编辑源代码]
类型安全配置[编辑 | 编辑源代码]
使用`@ConfigurationProperties`绑定属性到Java对象,避免硬编码键名:
@ConfigurationProperties(prefix = "mail")
public class MailProperties {
private String host;
private int port;
// Lombok注解生成Getter/Setter
}
配置加密[编辑 | 编辑源代码]
使用Jasypt或Spring Cloud Config加密敏感信息:
spring.datasource.password=ENC(加密后的密码)
总结[编辑 | 编辑源代码]
Spring Boot配置系统提供了高度灵活的方式管理应用程序行为,支持多环境、外部化配置和动态覆盖。通过合理使用配置优先级和条件化加载,开发者可以轻松适应不同部署场景。