Spring Boot 提供豐富的配置載入機制,支援 `.properties`、`.yml`、命令列參數、環境變數等多來源,並遵循優先級覆蓋規則。本文系統整理三種常見進階用法。
@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() { /* 定時任務 */ }
}
# 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
掌握配置載入機制,能讓專案在開發、測試、生產環境間無縫切換,也是雲原生十二要素中「配置與程式碼分離」的落地關鍵。