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

Spring Boot 載入 properties 與 YAML 配置檔完整指南

     編輯:Java 相關知識

Spring Boot 配置載入三大方式

Spring Boot 提供豐富的配置載入機制,支援 `.properties`、`.yml`、命令列參數、環境變數等多來源,並遵循優先級覆蓋規則。本文系統整理三種常見進階用法。

方式一:@PropertySource + Environment 注入

@Configuration
@PropertySource(ignoreResourceNotFound = true, 
    value = {"classpath:/config/email.properties", "classpath:/config/email.yml"}, 
    name = "email")
public class Config {}


AnnotationConfigEmbeddedWebApplicationContext ctx = 
    (AnnotationConfigEmbeddedWebApplicationContext) app.run(args);
ctx.register(Config.class);

Environment env = ctx.getEnvironment();
System.out.println(env.getProperty("address")); // 從 email.yml 讀取 server.address

⚠️ 注意:`@PropertySource` 原生不支援 YAML,需自訂 `PropertySourceFactory` 或改用 `@ConfigurationProperties`。

方式二:命令列參數注入

public class Main {
    public static void main(String[] args) {
        // 解析命令列 --greeting=Hello
        OptionParser parser = new OptionParser();
        parser.accepts("greeting").withRequiredArg();
        OptionSet options = parser.parse(args);
        
        // 轉為 Spring PropertySource
        PropertySource<?> ps = new JOptCommandLinePropertySource(options);
        
        // 裝載到 Environment
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.getEnvironment().getPropertySources().addLast(ps);
        ctx.register(Greeter.class);
        ctx.refresh();
        
        ctx.getBean(Greeter.class).sayGreeting();
    }
}

@Component
class Greeter {
    @Inject Environment env;
    public void sayGreeting() {
        System.out.println(env.getProperty("greeting", "Welcome!"));
    }
}

方式三:標準啟動類配置(推薦生產環境)

@Configuration
@EnableScheduling
@ComponentScan("com.mycompany.package")
@PropertySource(value = {
    "classpath:/application.properties", 
    "file:${config.location}"  // 支援外部檔案覆蓋
}, ignoreResourceNotFound = true)
class ApplicationConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

@Component
class MyComponent {
    @Value("${my.property.data}")
    private String myPropertyData;
    
    @Scheduled(fixedDelayString = "${schedule.delay.period}")
    public void run() { /* 定時任務 */ }
}

YAML 多環境配置範例

# application.yml
server:
  address: 127.0.0.1
  port: 8080

spring:
  profiles:
    active: dev  # 預設啟用 dev

---
# application-dev.yml
spring:
  datasource:
    url: jdbc:mysql://dev-db:3306/test
    username: dev_user

---
# application-prod.yml
spring:
  datasource:
    url: jdbc:mysql://prod-db:3306/test
    username: prod_user

配置優先級順序(高→低)

  1. 命令列參數 (`--key=value`)
  2. 系統環境變數 (`SPRING_APPLICATION_JSON` 等)
  3. 外部配置檔 (`file:config/application.yml`)
  4. 內部配置檔 (`classpath:application.yml`)
  5. @PropertySource 指定檔案
  6. 預設值 / `@Value` 默認值

最佳實踐建議

  • ✅ 主配置用 `application.yml`,環境差異用 `application-{profile}.yml`
  • ✅ 敏感資訊(密碼、金鑰)**絕不入倉**,用環境變數或配置中心注入
  • ✅ 使用 `@ConfigurationProperties` 綁定結構化配置,享受型別檢查與 IDE 提示
  • ✅ 啟用 `@PropertySource(ignoreResourceNotFound=true)` 避免缺檔報錯

掌握配置載入機制,能讓專案在開發、測試、生產環境間無縫切換,也是雲原生十二要素中「配置與程式碼分離」的落地關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved