Converter use and its principle

Source: Internet
Author: User

在Spring MVC开发中,我们可以很方便的使用Converter来实现对请求参数的处理,比如字符串去空,日期格式化等。配置文件中对Converter的引用:
<!--Property Editor --    <bean id= "conversionservice"class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean ">                < property name="Converters">            <list>                <Bean class="Com.xxx.common.converter.StringTrimConverter" />                <Bean class="Com.xxx.common.converter.DateConverter" />                <Bean class="Com.xxx.common.converter.DatetimeConverter" />            </list>        </Property >    </Bean><mvc:annotation-driven conversion-service="Conversionservice">

As the code above, we have configured three types of converter.
Take the string to empty for example,

Import Org.springframework.core.convert.converter.Converter;/** * Remove space before and after * @author * */ Public  class stringtrimconverter implements Converter<String, String> {     PublicString Convert (string source) {//Convert if the source string is not empty        if(Source! =NULL){//Remove space before and after source stringSource = Source.trim ();if(Source.equals ("") {Source =NULL; }        }returnSource }}

Configure the above content, you can implement the string in our request to automatically remove space.

Understanding the use is actually very simple, we can look at the bottom of spring, how to realize converter. Let's take a string to empty the code for example.
The above code, the first implementation of the converter interface, we look at the converter interface source code.

/** * A converter converts a source object of type S to A target of type T. * Implementations of this interface is th Read-safe and can be shared. * * <p>implementations may additionally implement {@link conditionalconverter}. * * @author Keith Donald * @since 3.0 * @see conditionalconverter * @param <S> T He source type * @param <T> the target type * /Public interface Converter<s, t> {/** * Convert The source of type S to target type T.  * @param Source The source object to convert, which must is an instance of S * @return the converted object, which must be a instance of T * @throws illegalargumentexception If the source could not being convert Ed to the desired target type * /T convert (S source);}

By Javadoc we can see that implementing this interface allows us to convert objects of type S to type T. Then the corresponding conversion of the date type can be written as the following code:
public class DateConverter implements Converter

id="conversionService"        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

The object of this class, continue to see the corresponding modification of the source code, as well as the corresponding Javadoc. We can see the following description in the doc for this class:

* <p>like all {@code Factorybean}  Implementations, this class  is  suitable for  * Use when configuring a Spring application context using  Spring {@code <beans>}  * XML. When configuring the container with  * {@link Org.springframework.context.annotation.Configuration @Configuration}  * classes, simply instantiate, configure and  return the appropriate * {@code Formattingconversionservice}  Object from  A * {@ Link Org.springframework.context.annotation.Bean @Bean}   method .  

This class is suitable for XML-built spring applications.
We look at the corresponding member variables:

 Public  class Formattingconversionservicefactorybeanimplements Factorybean< formattingconversionservice, embeddedvalueresolveraware, initializingbean {            PrivateSet<?> converters;PrivateSet<?> formatters;PrivateSet<formatterregistrar> Formatterregistrars;PrivateBoolean registerdefaultformatters =true;PrivateStringvalueresolver Embeddedvalueresolver;PrivateFormattingconversionservice Conversionservice;

When we configure XML, we mainly configure the converters of the collection class, which is more important than the following:

@Override    publicvoidafterPropertiesSet() {        thisnew DefaultFormattingConversionService(thisthis.registerDefaultFormatters);        ConversionServiceFactory.registerConverters(thisthis.conversionService);        registerFormatters();    }

This method implements the formatter for adding or subtracting our corresponding conversionservice.

When spring starts, the Afterpropertiesset method is entered when the converter is registered. In this method, we can see that spring takes hashset to store the corresponding converters. In Conversionservicefactory, the different converters are judged and registered.

 Public Staticvoid Registerconverters (Set<?> Converters, converterregistry Registry) {if(Converters! =NULL) { for(Object converter:converters) {if(ConverterinstanceofGenericconverter) {registry.addconverter (genericconverter) converter); }Else if(ConverterinstanceofConverter<?,?>) {Registry.addconverter (Converter<?,?>) converter); }Else if(ConverterinstanceofConverterfactory<?,?>) {Registry.addconverterfactory (converterfactory<?,?>) converter); }Else{Throw NewIllegalArgumentException ("Each converter object must implement one of the"+"Converter, converterfactory, or Genericconverter interfaces"); }            }        }    }

Converter use and its principle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.