码迷,mamicode.com
首页 > 其他好文 > 详细

Converter(转换器)与Formatter(格式化)

时间:2018-01-27 00:47:24      阅读:969      评论:0      收藏:0      [点我收藏+]

标签:version   org   注意   work   color   frame   style   parse   必须   

Converter(转换器)与Formatter(格式化)都可以用于将一种对象类型转换为另一种对象类型。Converter是通用元件,可以在应用程序的任意层中使用,而Foterrmatter这是专门为Web层设计的。

Converter

创建Converter,必须编写实现org.springframework.core.convert.converter.Converter接口的一个Java类。该接口的实现声明如下:

public interface Converter<S,T>

这里的S标识源类型,T表示目标类型。这是一个将String转为Employee对象的转换器:

public class EmployeeConveter implements Converter<String,Employee> {}

为了使用springMVC应用程序中定制的Converter,需要在springMVC配置文件中编写一个名为conversionService的bean。bean的类名称必须为org.springframeword.context.support.ConversionServiceFactoryBean。这个bean必须包含一个converters属性,它将列出要在应用程序中使用的所有定制Converter。

<!-- 配置自定义类型转换器 -->
<bean id="employeeConveter" class="cn.lynu.converter.EmployeeConveter"></bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
   <property name="converters">
     <set>
       <ref bean="employeeConveter"/>
     </set>
   </property>
</bean>

随后,要是annotation-driver元素的conversion-service属性赋值bean名称,如下:

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

Formatter

Formatter就像Converter一样,也是将一种类型转换为另一种类型。但是,Formatter的源类型必须是一个String,而Converter则适用用于任意源类型。Formatter更适合Web层,而Converter则可以用在任意层,为了转换SpringMVC应用程序表单中的用户输入,始终应该选择Formatter,而不是Converter。

为了创建Formatter,要编写一个实现org.springframework.format.Formatter接口的Java类。下面是这个接口的声明:

public interface Formatter<T>

这里的T表示输入字符串要转换的目标类型。

public class LocalDateFormatter implements Formatter<LocalDate> {}

该接口有parse和print两个方法。所有实现都必须覆盖它们。

T parse(String text,java.util.Locale locale)

String print(T object,java.util.Local local)

parse方法利用值当的Locale将一个String解析为String解析成目标类型。print方法与之相反,他返回目标对象的字符串表示法。

为了在springMVC中使用Formatter,需要利用名为conversionService的bean对它进行注册。bean的类名称必须为org.springframework.format.support.FormatterConversionServiceFactoryBean,这个bean可以用一个·formatters属性注册formatter,用一个converters属性注册converter。

    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="formatters">
            <set>
                <!--注册formatters-->
            </set>  
        </property>
    </bean>  

注意:formatters/converters都是set类型,我们还需要给这个Formatter添加一个component-scan元素:

<context:component-scan base-package="cn.lynu.formatter" />

或者是使用@Component注解

技术分享图片

随后,还要是annotation-driver元素的conversion-service属性赋值bean名称,如下:

<mvc:annotation-driven conversion-service="conversionService" />

 

Converter(转换器)与Formatter(格式化)

标签:version   org   注意   work   color   frame   style   parse   必须   

原文地址:https://www.cnblogs.com/lz2017/p/8361788.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!