Bean 配置中硬編碼文件路徑、數據源信息等部署細節,導致環境遷移需修改代碼。Spring 提供 PropertyPlaceholderConfigurer 將配置外部化到 .properties 文件,並在 XML 中用 ${var} 佔位符引用。
PropertyPlaceholderConfigurer 實現 BeanFactoryPostProcessor,在 Bean 實例化前替換佔位符。${key} 互相引用。<context:property-placeholder location="..."/> 自動注冊處理器。
abc=123456
cde=${abc}
<?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"
xmlns:p="https://www.springframework.org/schema/p"
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">
<!-- 載入屬性文件,自動註冊 PropertyPlaceholderConfigurer -->
<context:property-placeholder location="db.properties"/>
<!-- 使用 ${...} 引用屬性 -->
<bean class="com.nucsoft.spring.bean.Employee" id="employee"
p:empName="${abc}" p:age="${cde}" scope="prototype"/>
</beans>
@Test
public void test01() {
Employee employee = ctx.getBean(Employee.class);
System.out.println(employee);
}
Employee{empName='123456', age=123456}
location="classpath:db.properties,classpath:redis.properties"systemPropertiesModeName="SYSTEM_PROPERTIES_MODE_OVERRIDE",JVM -D 參數優先級更高。ignore-unresolvable="true" 防止啟動失敗。placeholderPrefix="%{" placeholderSuffix="}" 避免衝突。Spring Boot 推薦使用 @ConfigurationProperties + application.yml,提供類型安全綁定、鬆綁驗證、Profile 多環境隔離,功能更強大。但理解 PropertyPlaceholderConfigurer 有助於維護老專案及掌握 Spring 核心容器擴展點。