Properties 文件採用 key=value 鍵值對格式,支援註釋(# 或 ! 開頭),是 Java 應用最常用的配置文件格式。
# 數據庫配置
db.host=localhost
db.port=3306
db.name=myapp
db.user=root
db.password=secret
# 服務器配置
server.port=8080
server.context-path=/api
Properties 繼承自 Hashtable,提供以下關鍵方法:
load(InputStream) / load(Reader):加載配置getProperty(String key) / getProperty(String key, String defaultValue):讀取值setProperty(String key, String value):設置值store(OutputStream, String comments) / store(Writer, String comments):持久化public Properties loadFromFile(String filePath) throws IOException {
Properties props = new Properties();
try (FileInputStream fis = new FileInputStream(filePath)) {
props.load(fis);
}
return props;
}
public Properties loadFromClasspath(String resourcePath) throws IOException {
Properties props = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream(resourcePath)) {
if (is == null) {
throw new IllegalArgumentException("配置文件不存在: " + resourcePath);
}
props.load(is);
}
return props;
}
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${db.host}")
private String dbHost;
@Value("${db.port:3306}") // 支持默認值
private int dbPort;
// 注入整個 Properties 對象
@Autowired
private Environment env;
public void printAll() {
System.out.println("DB Host: " + dbHost);
System.out.println("DB Port: " + dbPort);
}
}
Properties 默認使用 ISO-8859-1 編碼讀取。Java 9+ 可直接用 load(Reader) 指定 UTF-8:
try (FileReader reader = new FileReader(filePath, StandardCharsets.UTF_8)) {
props.load(reader);
}
舊版本需手動轉碼:
String value = new String(props.getProperty("key").getBytes("ISO-8859-1"), "UTF-8");
# application-dev.properties
# application-prod.properties
# application-test.properties
# Spring Boot 啟動時指定:--spring.profiles.active=prod
@Data
@ConfigurationProperties(prefix = "db")
@Component
public class DatabaseProperties {
private String host;
private int port;
private String name;
private String username;
private String password;
}
src/main/resources,使用 ClassPath 加載getProperty(key, defaultValue) 提供合理默認值ConfigUtil 工具類,集中管理加載邏輯掌握 Properties 文件的正確讀取姿勢,能讓應用配置更靈活、部署更簡單、維護更輕鬆。