Spring 提供 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 在容器啟動階段加載屬性文件,支援 XML 佔位符 ${key} 與注解 @Value("${key}") 兩種注入方式。
# 郵件服務器配置 email.host=smtp.exmail.qq.com email.port=465 email.username=notify@example.com email.password=secret123 email.sendFrom=notify@example.com
<!-- 屬性文件加載器 -->
<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>
@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; }
}
# 文件存儲路徑 file.savePath=D:/test/ file.backupPath=D:/test_bak/
@Service
public class FileProcessService {
@Autowired
private ConfigInfo configInfo;
public void process() {
String saveDir = configInfo.getFileSavePath();
String bakDir = configInfo.getFileBakPath();
// 業務邏輯...
}
}
<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 覆蓋通用配置。