專案中頻繁變更的參數(數據庫連接、文件路徑、第三方密鑰)應外部化至 Properties 文件。Spring 提供兩種加載機制:基於 XML 的佔位符替換、基於註解的 @Value 注入,本文對比兩種模式適用場景與配置細節。
<context:property-placeholder>)conn.propertiesdataSource=com.mchange.v2.c3p0.ComboPooledDataSource
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\://localhost\:3306/shop
user=root
password=root
beans.xml 配置<context:property-placeholder location="classpath:conn.properties"/>
<bean id="dataSource" class="${dataSource}">
<property name="driverClass" value="${driverClass}"/>
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
</bean>
啟動時 Spring 解析 ${key} 替換為 Properties 值,適用於 Bean 定義階段的屬性注入。
<bean> 寫法(可讀性更強)<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array><value>classpath:conn.properties</value></array>
</property>
</bean>
PropertyPlaceholderConfigurer 支持多文件數組,優先級按順序遞減。
@Value + PropertiesFactoryBean)public.propertiesfilePath=E\:\\web\\apache-tomcat-8.0.26\\webapps\\E_shop\\image
beans.xml 註冊 PropertiesFactoryBean<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<array><value>classpath:public.properties</value></array>
</property>
</bean>
@Component("fileUpload")
public class FileUploadUtil implements FileUpload {
private String filePath;
@Value("#{prop.filePath}")
public void setFilePath(String filePath) {
System.out.println(filePath); // 啟動日誌驗證注入成功
this.filePath = filePath;
}
}
關鍵點:
@Value("#{prop.filePath}"):SpEL 表達式,引用 Bean prop 的屬性 filePath@Autowired 配合| 維度 | XML 佔位符 | @Value 註解 |
|---|---|---|
| 適用範圍 | Bean 定義元數據(class、property) | Java 代碼邏輯(字段、方法參數) |
| 多文件支持 | locations 數組 | 多個 PropertiesFactoryBean 或合併文件 |
| 類型轉換 | 自動轉換基本類型 | 同樣支持,SpEL 表達式更強 |
| 可讀性 | 集中聲明,適合基礎設施配置 | 分散在業務代碼,適合業務參數 |
| 熱加載 | 不支持 | 不支持(需 Spring Cloud Config/Apollo) |
PropertyPlaceholderConfigurer 與 PropertiesFactoryBean 均繼承 PropertiesLoaderSupport,底層均通過 PropertiesLoaderUtils.loadProperties() 讀取資源文件。本質相同,只是注入切入點不同。
@Value 注入(文件路徑、第三方密鑰、分頁大小、開關標誌)掌握雙模式,讓配置管理既規範又靈活。