Spring 容器預設不支援直接將字串轉換為 java.util.Date,需透過自定義 PropertyEditor 實現。本文示範如何結合多配置檔實現日期屬性的靈活注入。
package com.zhmg.spring;
import java.util.Date;
public class DatePropertyInjection {
private Date date;
public Date getDate() { return date; }
public void setDate(Date date) { this.date = date; }
}
繼承 PropertyEditorSupport,覆寫 setAsText() 解析字串為 Date,支援可配置的日期格式:
package com.zhmg.spring;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PropertyEditor extends PropertyEditorSupport {
private String format = "yyyy-MM-dd"; // 預設格式
public void setFormat(String format) { this.format = format; }
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date date = sdf.parse(text);
setValue(date);
} catch (ParseException e) {
throw new IllegalArgumentException("日期解析失敗: " + text, e);
}
}
}
applicationContextBeans.xml 定義 Bean 並註冊 CustomEditorConfigurer:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="dateProperty" class="com.zhmg.spring.DatePropertyInjection">
<property name="date"><value>2009-8-28</value></property>
</bean>
<!-- 註冊全域日期編輯器 -->
<bean id="editor" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.zhmg.spring.PropertyEditor">
<property name="format" value="yyyy-MM-dd"/> <!-- 注入日期格式 -->
</bean>
</entry>
</map>
</property>
</bean>
</beans>
使用通配符載入所有 applicationContext*.xml:
package com.zhmg.spring;
import junit.framework.TestCase;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class InjectionTest extends TestCase {
private BeanFactory factory;
protected void setUp() {
factory = new ClassPathXmlApplicationContext("applicationContext*.xml");
}
public void testInjection() {
DatePropertyInjection bean = (DatePropertyInjection) factory.getBean("dateProperty");
System.out.println("date = " + bean.getDate()); // 輸出: Fri Aug 28 00:00:00 CST 2009
}
}
CustomEditorConfigurer 可註冊全域屬性編輯器,對所有 java.util.Date 類型屬性生效。<property> 注入格式參數,實現「配置即代碼」。applicationContext*.xml)便於模組化管理。此模式廣泛適用於任何需自定義類型轉換的場景(如枚舉、自定義值對象等)。