Spring 自定义属性编辑(CustomEditorConfigurer)和类型转换器(ConversionServiceFactoryBean)一起配置问题
问题:
现在这样一种需求, 有一个bean它的属性是java.util.Date类型,我们要在spring的xml配置初始化它,怎么做呢
解决方案:可以说spring的属性编辑器和类型转换器都是做类型转换的,但属性编辑器多为string转其它类型,方法1:添加属性编辑器:
Configuring a ConversionService
A ConversionService is a stateless object designed to be instantiated at application startup, then shared between multiple threads. In a Spring application, you typically configure a ConversionService instance per Spring container (or ApplicationContext). That ConversionService will be picked up by Spring and then used whenever a type conversion needs to be performed by the framework. You may also inject this ConversionService into any of your beans and invoke it directly.
Note If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.
To register a default ConversionService with Spring, add the following bean definition with id
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/>
A default ConversionService can convert between strings, numbers, enums, collections, maps, and other common types. To suppliment or override the default converters with your own custom converter(s), set the 告诉我们可能实以 Converter, ConverterFactory, or GenericConverter这三个接口中的一个和相应配置来补充类型转换 bug描述 : https://jira.springsource.org/browse/SPR-6807 其中说到: ConversionService fails with CustomEditorConfigurer. While it is not recommended to mix the two in the same context it is unavoidable spring 相关api: http://static.springsource.org/spring/docs/3.0.x/reference/validation.html<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="example.MyCustomConverter"/> </list> </property></bean>以上为spring 官方reference关于注册类型转换器的介绍,其中说到"To suppliment or override the default converters with your own custom converter(s), set the converters property. Property values may implement either of the Converter, ConverterFactory, or GenericConverter interfaces."import java.text.ParseException;import java.util.Date;import org.apache.commons.lang.time.DateUtils;import org.springframework.core.convert.converter.Converter;public class String2DateConverter implements Converter<String, Date> {@Overridepublic Date convert(String arg0) {try {return DateUtils.parseDate(arg0,new String[] { "yyyy-MM-dd HH:mm:ss" });} catch (ParseException e) {return null;}}}
