自定义属性转换器
- 首先新建一个类继承PropertyEditorSupport
- 然后重新setAsText(String text);方法
- 最后在Spring配置文件中配置该类的引用
·示例代码·
/**
*自定义一个时间转换器
*/
public class UtilDatePropertyEditor extends PropertyEditorSupport{
//定义时间格式的字符串
private String formatContext;
@override
public void setAsText(String text) throws IllegalArgumentException{
//将传入的时间字符串按照设置的格式格式化
Date date = new SimpleDateFormat(formatContext).parse(text);
this.setValue(date);
}catch(ParseException e){
e.printStackTrace();
}
}
//setter..
public String setFormatContext(String formatContext){
this.formatContext = formatContext;
}
}
Spring中的配置
<!-- org.springframework.beans.factory.config.CustomEditor 这是一个Spring提供的类,用来自定义属性转换器 -->
<bean id="customEditor" class="org.springframework.beans.factory.config.CustomEditor" >
<!-- customEditors属性是一个Map类型,用来存储自定义属性转换器 -->
<property name="customEditors" >
<map>
<!-- Map的key值保存的是数据类型 -->
<entry key="java.util.Date" >
<!-- 将我们自定义的编辑器放入Map的value中 -->
<!-- 也可以将该类单独配置在entry中用value-ref引用 -->
<bean class="com.util.UtilDatePropertyEditor">
<!-- 注入需要转换的格式类型 -->
<property name="formatContext" value="yyyy-MM-dd" />
</bean>
</entry>
</map>
</property>
</bean>
<!-- 如下某个类 -->
<bean id="someClass" class="packageName.SomeClassName">
<!-- 某个java.util.Date类型属性 -->
<property name="dateValue" value="2099-12-31" />
</bean>