05.3 — 外部化配置与 Actuator
外部化配置让应用在不同环境中灵活切换,Actuator 为生产环境提供监控和管理能力。
← 返回 **Spring Boot 索引**
1. 内嵌容器
切换容器
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>各容器对比
| 容器 | 特点 | 适用场景 |
|---|---|---|
| Tomcat | 默认,稳定成熟 | 通用场景 |
| Jetty | 轻量,启动快 | 微服务、短生命周期应用 |
| Undertow | 高并发,低内存 | I/O 密集型,高负载场景 |
容器定制
yaml
server:
port: 8080
tomcat:
max-threads: 200
max-connections: 10000
accept-count: 100
connection-timeout: 5000java
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
factory.addConnectorCustomizers(connector -> {
connector.setProperty("maxKeepAliveRequests", "100");
});
return factory;
}2. 外部化配置加载顺序
yaml
# 优先级从高到低
# 1. @TestPropertySource(测试注解)
# 2. 命令行参数 --spring.profiles.active=dev --server.port=8081
# 3. JNDI 属性 java:comp/env
# 4. Java 系统属性 System.getProperties()
# 5. OS 环境变量
# 6. application-{profile}.yml(profile-specific,按 profile 从高到低)
# 7. application.yml(最后,默认值)Profile 特定配置
yaml
# application.yml(通用配置)
spring:
datasource:
url: jdbc:h2:mem:testdb
# application-dev.yml(开发环境)
spring:
datasource:
url: jdbc:mysql://localhost:3306/dev_db
# application-prod.yml(生产环境)
spring:
datasource:
url: jdbc:mysql://prod-db:3306/prod_db3. 外部化配置方式
| 方式 | 示例 | 适用场景 |
|---|---|---|
@Value | @Value("${app.name}") | 单个配置值 |
@ConfigurationProperties | @ConfigurationProperties(prefix = "app") | 绑定一组配置到 POJO |
Environment | env.getProperty("app.name") | 编程式获取 |
@PropertySource | @PropertySource("classpath:custom.properties") | 加载自定义配置文件 |
@ConfigurationProperties 示例
java
@Component
@ConfigurationProperties(prefix = "app.datasource")
@Data // Lombok
public class DataSourceProperties {
private String url;
private String username;
private String password;
private Pool pool = new Pool();
@Data
public static class Pool {
private int maxSize = 10;
private int minIdle = 2;
}
}yaml
app:
datasource:
url: jdbc:mysql://localhost:3306/db
username: root
password: secret
pool:
max-size: 20
min-idle: 54. Actuator
常用端点
| 端点 ID | 说明 | 默认启用 |
|---|---|---|
health | 健康检查 | ✅ |
info | 应用信息 | ✅ |
metrics | 应用指标 | ✅ |
env | 环境属性 | ❌ |
beans | 所有 Bean | ❌ |
mappings | URL 映射 | ❌ |
loggers | 日志级别 | ❌ |
threaddump | 线程转储 | ❌ |
heapdump | 堆转储 | ❌ |
shutdown | 关闭应用 | ❌ |
配置 Actuator
yaml
management:
endpoints:
web:
exposure:
include: health,info,metrics,env,beans # 暴露的端点
base-path: /actuator # 端点前缀
endpoint:
health:
show-details: always # 显示详细健康信息自定义 HealthIndicator
java
@Component
public class DatabaseHealthIndicator implements HealthIndicator {
@Autowired
private DataSource dataSource;
@Override
public Health health() {
try (Connection conn = dataSource.getConnection()) {
if (conn.isValid(1000)) {
return Health.up()
.withDetail("database", "MySQL")
.withDetail("status", "connected")
.build();
}
return Health.down()
.withDetail("database", "unreachable")
.build();
} catch (Exception e) {
return Health.down(e).build();
}
}
}常见面试题
- application.yml 和 application-{profile}.yml 的优先级?
- 如何将配置文件的属性绑定到 Java Bean?@Value 和 @ConfigurationProperties 的区别?
- Actuator 的安全如何保障?
- 如何切换 Spring Boot 的内嵌 Servlet 容器?
← 返回 **Spring Boot 索引**