本文目录导读:

我来详细讲解Java中YAML配置文件的编写方法,包含多个实际案例。
基础YAML配置案例
1 添加依赖
Maven依赖
<!-- Spring Boot项目已内置 -->
<!-- 单独使用需添加 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>2.2</version>
</dependency>
2 基础配置文件(application.yml)
# 服务器配置
server:
port: 8080
servlet:
context-path: /api
# 数据库配置
database:
url: jdbc:mysql://localhost:3306/myapp
username: root
password: ${DB_PASSWORD:password123} # 支持环境变量
driver-class-name: com.mysql.cj.jdbc.Driver
pool:
initial-size: 5
max-active: 20
min-idle: 5
# 应用配置
app:
name: "My Application"
version: 1.0.0
debug: true
languages:
- zh-CN
- en-US
- ja-JP
使用@ConfigurationProperties注解
1 创建配置类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private String version;
private boolean debug;
private List<String> languages;
private DatabaseConfig database;
// 嵌套配置类
public static class DatabaseConfig {
private String url;
private String username;
private String password;
private String driverClassName;
private PoolConfig pool;
// getters and setters
// ...
}
public static class PoolConfig {
private int initialSize;
private int maxActive;
private int minIdle;
// getters and setters
// ...
}
// getters and setters
}
2 启用配置属性
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties({AppConfig.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
复杂YAML配置案例
1 多环境配置
application-dev.yml
server:
port: 8081
database:
url: jdbc:mysql://localhost:3306/dev_db
username: dev_user
password: dev_pass
logging:
level:
root: DEBUG
com.example: TRACE
application-prod.yml
server:
port: 8080
database:
url: jdbc:mysql://production:3306/prod_db
username: prod_user
password: ${PROD_DB_PASSWORD}
logging:
level:
root: WARN
com.example: INFO
2 集合和复杂结构
# 复杂配置案例
feature-flags:
- name: new-payment-system
enabled: true
rollout-percentage: 50
description: "新支付系统"
metadata:
team: payment-team
jira-ticket: PAY-1234
created-date: 2024-01-15
- name: dark-mode
enabled: ${DARK_MODE_ENABLED:false}
rollout-percentage: 100
description: "暗黑模式"
metadata:
team: ui-team
jira-ticket: UI-5678
created-date: 2024-02-01
# 映射配置
cache:
providers:
redis:
host: ${REDIS_HOST:localhost}
port: ${REDIS_PORT:6379}
timeout: 5000
pool:
max-total: 16
max-idle: 8
local:
max-size: 1000
ttl: 3600
读取YAML配置的多种方式
1 使用@Value注解
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class ConfigService {
@Value("${app.name}")
private String appName;
@Value("${database.url}")
private String databaseUrl;
@Value("${server.port:8080}") // 设置默认值
private int port;
@Value("#{'${app.languages}'.split(',')}")
private List<String> languages;
public void printConfig() {
System.out.println("App Name: " + appName);
System.out.println("Database URL: " + databaseUrl);
System.out.println("Port: " + port);
}
}
2 使用SnakeYAML直接解析
import org.yaml.snakeyaml.Yaml;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;
public class YamlParser {
public static Map<String, Object> parseYaml(String filePath) {
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(filePath)) {
return yaml.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static <T> T parseYaml(String filePath, Class<T> type) {
Yaml yaml = new Yaml();
try (InputStream inputStream = new FileInputStream(filePath)) {
return yaml.loadAs(inputStream, type);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
实用配置案例
1 线程池配置
thread-pool: core-size: 10 max-size: 50 keep-alive-seconds: 60 queue-capacity: 100 thread-name-prefix: "async-" rejected-execution-handler: "CallerRunsPolicy"
@Component
@ConfigurationProperties(prefix = "thread-pool")
public class ThreadPoolConfig {
private int coreSize;
private int maxSize;
private int keepAliveSeconds;
private int queueCapacity;
private String threadNamePrefix;
private String rejectedExecutionHandler;
public ExecutorService createExecutor() {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
coreSize,
maxSize,
keepAliveSeconds,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(queueCapacity),
new ThreadFactoryBuilder()
.setNameFormat(threadNamePrefix + "%d")
.build(),
new ThreadPoolExecutor.CallerRunsPolicy()
);
return executor;
}
// getters and setters
}
2 邮件配置
mail:
host: smtp.gmail.com
port: 587
username: ${MAIL_USERNAME}
password: ${MAIL_PASSWORD}
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.connectiontimeout: 5000
mail.smtp.timeout: 5000
mail.smtp.writetimeout: 5000
default-encoding: UTF-8
templates:
welcome: classpath:/templates/welcome.html
reset-password: classpath:/templates/reset-password.html
notification: classpath:/templates/notification.html
配置验证
import javax.validation.constraints.*;
import org.springframework.validation.annotation.Validated;
@Component
@ConfigurationProperties(prefix = "app")
@Validated
public class ValidatedConfig {
@NotBlank(message = "应用名称不能为空")
private String name;
@NotNull
@Pattern(regexp = "^\\d+\\.\\d+\\.\\d+$", message = "版本号格式错误")
private String version;
@Min(value = 1024, message = "端口号最小为1024")
@Max(value = 65535, message = "端口号最大为65535")
private int port;
@Email(message = "邮箱格式不正确")
private String contactEmail;
@NotEmpty(message = "语言列表不能为空")
private List<String> languages;
// getters and setters
}
动态刷新配置
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
@ConfigurationProperties(prefix = "dynamic")
public class DynamicConfig {
private String featureFlag;
private int maxRetries;
private Map<String, String> mappings;
// getters and setters
}
最佳实践建议
- 使用降级默认值:为关键配置提供默认值
- 环境变量覆盖:支持通过环境变量覆盖配置
- 配置分组:按功能模块组织配置
- 敏感信息加密:使用加密工具处理密码等敏感信息
- 配置校验:使用@Validated进行验证
- 文档注释:在YAML中添加注释说明
这些案例覆盖了Java中YAML配置的主要使用场景,可以根据实际需求选择合适的方式。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播