首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring Boot 讀取 YAML 與 Properties 配置的最佳實踐:@ConfigurationProperties 與 @Value 深度解析

     編輯:Java 相關知識

兩大配置格式對比

特性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 輕量注入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved