兩大配置格式對比
| 特性 | YAML (.yml) | Properties (.properties) |
| 層級結構 | 原生支援巢狀 | 扁平鍵值,靠前綴模擬層級 |
| 資料型別 | 豐富(List、Map、Boolean) | 僅字串,需手動轉型 |
| 註解支援 | 支援 # 註解 | 支援 # ! 註解 |
| @PropertySource | 不支援(Spring 4.1+ 需自定義 Factory) | 原生支援 |
| 適用場景 | 主配置、複雜結構 | 環境差異化、簡單鍵值、舊專案遷移 |
一、YAML 配置綁定:@ConfigurationProperties
1. 依賴準備
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2. application.yml 範例
myYml:
simpleProp: simpleValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Value2
mapProps:
key1: value1
key2: value2
3. 綁定類(支援鬆散綁定、JSR-303 校驗)
@Component
@ConfigurationProperties(prefix = "myYml")
@Validated
public class YmlConfig {
private String simpleProp;
private String[] arrayProps; // 逗號分隔自動轉陣列
private List<Map<String, String>> listProp1 = new ArrayList<>();
private List<String> listProp2 = new ArrayList<>();
private Map<String, String> mapProps = new HashMap<>();
// Getter/Setter 省略...
}
4. 注入使用
@Autowired private YmlConfig config;
public void print() {
ObjectMapper om = new ObjectMapper();
System.out.println("simpleProp: " + config.getSimpleProp());
System.out.println("arrayProps: " + om.writeValueAsString(config.getArrayProps()));
System.out.println("listProp1: " + om.writeValueAsString(config.getListProp1()));
System.out.println("listProp2: " + om.writeValueAsString(config.getListProp2()));
System.out.println("mapProps: " + om.writeValueAsString(config.getMapProps()));
}
二、Properties 配置綁定:@PropertySource + @Value
1. 專用配置類
@Configuration
@PropertySource(value = {"classpath:/config/app.properties",
"classpath:/config/optional.properties"},
ignoreResourceNotFound = true,
encoding = "UTF-8")
public class PropConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer(); // 解析 ${...}
}
}
2. 兩種注入方式
@Component
public class PropConsumer {
// 方式一:Environment(適合動態鍵、批量讀取)
@Autowired private Environment env;
// 方式二:@Value(適合固定鍵、編譯期檢查)
@Value("${app.name}") private String appName;
@Value("${server.port:8080}") private int port; // 預設值
public void demo() {
System.out.println(env.getProperty("app.name"));
System.out.println(appName + ":" + port);
}
}
三、進階技巧與避坑指南
| 場景 | 解決方案 |
| YAML 多環境隔離 | spring.profiles.active=dev + application-dev.yml |
| 動態刷新配置 | 引入 spring-cloud-starter-config + @RefreshScope |
| 加密敏感值 | 使用 jasypt-spring-boot 加密 password 欄位 |
| List/Map 綁定失效 | 確保目標屬性已初始化 new ArrayList<>(),且提供 Setter |
| 中文亂碼 | Properties 指定 encoding="UTF-8";YAML 預設 UTF-8 無需配置 |
四、選型建議
- 新專案優先 YAML,結構清晰、型別安全、IDE 提示友好;
- 需與舊系統共享配置、或透過環境變數注入時使用 Properties;
- 核心業務配置用
@ConfigurationProperties 統一管理,零散參數用 @Value 輕量注入。