Java配置管理:灵活管理应用配置
Java配置管理:灵活管理应用配置
概述
配置管理是应用开发的重要部分,它决定了应用如何在不同环境中运行。Java提供了多种配置方式,包括Properties、YAML和环境变量等。
1. Properties文件
import java.util.Properties;
import java.io.*;
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
Properties props = new Properties();
props.load(new FileInputStream("app.properties"));
String dbUrl = props.getProperty("database.url");
String dbUser = props.getProperty("database.user", "root");
int dbPort = Integer.parseInt(props.getProperty("database.port", "3306"));
System.out.println("URL: " + dbUrl);
System.out.println("User: " + dbUser);
System.out.println("Port: " + dbPort);
}
}
2. YAML配置
app:
name: MyApp
version: 1.0.0
database:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: ${DB_PASSWORD:123456}
logging:
level:
root: INFO
com.example: DEBUG
3. 环境变量
public class EnvironmentDemo {
public static void main(String[] args) {
String dbPassword = System.getenv("DB_PASSWORD");
String port = System.getenv("SERVER_PORT");
System.out.println("DB Password: " + dbPassword);
System.out.println("Server Port: " + port);
}
}
4. 多环境配置
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
---
spring:
config:
activate:
on-profile: prod
server:
port: 80
最佳实践
- 外部化配置:不要硬编码配置值
- 使用YAML:比Properties更易读
- 环境变量:敏感配置使用环境变量
- Profile机制:区分不同环境配置
- 配置加密:敏感配置加密存储
总结
配置管理是应用开发的重要部分,掌握Properties、YAML、环境变量等配置方式,可以实现灵活的多环境配置。