萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Spring 讀取 XML 配置文件完整實戰:從 Bean 定義到屬性注入

場景:系統配置外部化管理

將業務參數、環境差異化配置剝離代碼,通過 Spring 容器統一加載管理。

完整實現步驟

1. 定義配置 Bean


package com.example.config;

public class AppConfig {
    private String apiEndpoint;
    private int timeout;
    private boolean debugMode;
    
    // Getter/Setter 省略
    // 建議使用 Lombok @Data
}

2. 編寫 XML 配置文件 (application-config.xml)


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="
         https://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         https://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 啟用屬性佔位符解析 -->
    <context:property-placeholder location="classpath:app.properties" />

    <bean id="appConfig" class="com.example.config.AppConfig">
        <property name="apiEndpoint" value="${api.endpoint}" />
        <property name="timeout" value="${api.timeout:5000}" /> <!-- 默認值 -->
        <property name="debugMode" value="${debug:false}" />
    </bean>
</beans>

3. 屬性文件 (app.properties)


api.endpoint=https://api.example.com/v1
api.timeout=3000
debug=true

4. Spring 容器加載與使用


// Spring XML 裝配方式
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml");
AppConfig config = ctx.getBean(AppConfig.class);

// 或註解驅動方式 (推薦)
@Configuration
@PropertySource("classpath:app.properties")
public class ConfigLoader {
    @Autowired Environment env;
    
    @Bean
    public AppConfig appConfig() {
        AppConfig cfg = new AppConfig();
        cfg.setApiEndpoint(env.getProperty("api.endpoint"));
        cfg.setTimeout(env.getProperty("api.timeout", Integer.class, 5000));
        cfg.setDebugMode(env.getProperty("debug", Boolean.class, false));
        return cfg;
    }
}

進階特性

多環境配置隔離


# application-dev.properties
api.endpoint=https://dev.api.com

# application-prod.properties
api.endpoint=https://api.example.com

# 啟動時指定 profile
-Dspring.profiles.active=prod

配置加密解密 (Jasypt)


# pom.xml

    com.github.ulisesbocchio
    jasypt-spring-boot-starter


# 應用
api.password=ENC(G3x9K2mP...) # 加密值

動態刷新 (Spring Cloud Config / Apollo)

配合 @RefreshScope 實現無重啟配置更新。

最佳實踐總結

  1. 配置與代碼分離,環境差異外部化
  2. 敏感信息加密存儲,密鑰單獨管理
  3. 提供默認值增強魯棒性
  4. 使用構建工具(Maven/Gradle)進行資源過濾
  5. 微服務架構採用配置中心統一管理
copyright © 萬盛學電腦網 all rights reserved