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

Spring 框架中 Properties 配置文件加載與使用的兩種最佳實踐

     編輯:Java 綜合教學

核心工具類:PropertyPlaceholderConfigurer

Spring 提供 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 在容器啟動階段加載屬性文件,支援 XML 佔位符 ${key} 與注解 @Value("${key}") 兩種注入方式。

方式一:XML 佔位符直接注入 Bean 屬性

1. 定義屬性文件:configInfo.properties

# 郵件服務器配置
email.host=smtp.exmail.qq.com
email.port=465
email.username=notify@example.com
email.password=secret123
email.sendFrom=notify@example.com

2. Spring XML 配置加載器

<!-- 屬性文件加載器 -->
<bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/configInfo.properties"/>
    <property name="fileEncoding" value="utf-8"/>
</bean>

<!-- 郵件發送器 Bean,直接引用屬性佔位符 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${email.host}"/>
    <property name="port" value="${email.port}"/>
    <property name="username" value="${email.username}"/>
    <property name="password" value="${email.password}"/>
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
            <prop key="sendFrom">${email.sendFrom}</prop>
        </props>
    </property>
</bean>

方式二:Java 代碼中通過 @Value 注入(推薦用於業務邏輯)

1. 定義配置 Bean:ConfigInfo.java

@Component("configInfo")
public class ConfigInfo {
    @Value("${file.savePath}")
    private String fileSavePath;

    @Value("${file.backupPath}")
    private String fileBakPath;

    // Getter 省略
    public String getFileSavePath() { return fileSavePath; }
    public String getFileBakPath() { return fileBakPath; }
}

2. 屬性文件補充

# 文件存儲路徑
file.savePath=D:/test/
file.backupPath=D:/test_bak/

3. 業務類中自動裝配使用

@Service
public class FileProcessService {
    @Autowired
    private ConfigInfo configInfo;

    public void process() {
        String saveDir = configInfo.getFileSavePath();
        String bakDir = configInfo.getFileBakPath();
        // 業務邏輯...
    }
}

4. 啟用組件掃描(XML 或註解均可)

<context:component-scan base-package="com.my.model"/>

兩種方式對比與選型建議

維度XML 佔位符 ${key}@Value 注入配置 Bean
適用場景基礎設施 Bean 配置(數據源、郵件、Redis 等)業務代碼中動態獲取配置值
修改成本僅改屬性文件,無需動 Java 代碼新增屬性需修改 ConfigInfo 類添加字段
類型安全運行時轉換,易出錯編譯期類型檢查,IDE 提示友好
測試友好難以在單元測試中覆蓋可輕鬆 Mock ConfigInfo Bean

進階技巧:多環境配置隔離

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:config/common.properties</value>        <!-- 通用配置 -->
            <value>classpath:config/${spring.profiles.active}.properties</value> <!-- 環境專屬 -->
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true"/> <!-- 允許缺失 -->
    <property name="fileEncoding" value="utf-8"/>
</bean>

啟動時指定 -Dspring.profiles.active=dev 即可加載 dev.properties 覆蓋通用配置。

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