Spring中的类型转换与数据绑定(PropertyEditor、ConversionService、Data Binding、Formatter)

Spring早期使用PropertyEditor进行Object与String的转换。
到Spring 3后,Spring提供了统一的ConversionService API和强类型的Converter SPI,以实现转换逻辑。Spring容器使用该系统来绑定bean property values。
但是,除了格式转换,你还经常需要本地化String values。也就是以当地格式展示,如货币、日期等。通用的core.convert Converter SPI不能直接完成格式化需求。基于此,Spring 3 引入了 Formatter SPI,相比PropertyEditors简单直接。
ConversionService 为Converter SPI和Formatter SPI提供了统一的 API。

PropertyEditor: Spring早期使用PropertyEditor进行Object与String的转换。
ConversionService:Spring 3 引入了core.convert 包,提供了通用的类型转换系统。
Data Binding: Spring web中用来解析参数字符类型的参数,并绑定到实体中 Formatter:Spring 3 引入了 Formatter SPI,相比PropertyEditors简单直接。

Spring应用中,不会自动注册ConversionService bean,就是说默认基于PropertyEditor。

相关类和接口

ConversionService:这是Spring 类型转换体系的核心接口
ConversionServiceFactoryBean:这个相当于是类型转换器的容器,里面可以配置很多个转换器
转换器接口:
Converter:最简单的转换器接口,将S类型转为T类型
ConverterFactory:将S类型转换为另一种类型T及其子类型R的转换器接口。将相同系列多个Converter封装到一起
GenericConverter:相对于Converter接口,该接口会根据源类型与目标类型的上下文信息进行转换

参考:
http://www.cnblogs.com/sonng/p/6658825.html
http://www.cnblogs.com/larryzeal/p/5951196.html
http://www.cnblogs.com/larryzeal/p/5953391.html
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#format-configuring-formatting-globaldatetimeformat
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#format-CustomFormatAnnotations

posted on 2017-06-29 11:13  快鸟  阅读(950)  评论(0编辑  收藏  举报