6.5 Spring3 type Conversion

Source: Internet
Author: User

6.5Spring3Type Conversions

Spring3 introduced the Core.convert package, which provides a common type conversion system. The system defines an SPI to implement the type conversion logic. The SPI, like the API, is used to perform type conversions at run time. In the spring container, this system can be used instead of propertyeditors because it can also convert the Bean's string property value to the desired property type . In your application, you can use these public APIs wherever you need type conversions. (The converter below will be translated into converters)


Converter SPI

The SPI that implements the type conversion logic is simple and strongly typed:

Package Org.springframework.core.convert.converter;public Interface Converter<s, t> {T convert (S source);}

To create your own converter, you only need to implement the above interface. The parameter S is the type before the conversion, and T is the converted type. Each time you call convert (S), the parameter (the original value) cannot be null. Your converter may throw an exception if the conversion fails. If an invalid original value, then a illegalargumentexception should be thrown. And make sure that your converter implementation is thread-safe.

For convenience, some converter implementation classes are provided in the Core.convert.support package. This includes the conversion between string and number and other common types. The following converter implementation class--stringtointeger can be used as a small example to learn:

Package Org.springframework.core.convert.support;final class Stringtointeger implements Converter<string, Integer > {public Integer convert (String source) {return integer.valueof (source);}}


Converter Factory

When you need to centralize the transformation logic for a complete class structure, for example, a conversion from string to Java.lang.Enum, implement Converterfactory.

Package Org.springframework.core.convert.converter;public Interface Converterfactory<s, r> {<T extends R> Converter<s, t> getconverter (class<t> targetType);}

The parameter S is the type of the parameter before the conversion, and the parameter r is the base type of the class you are converting to, which defines the range of classes you can convert. Then you need to implement Getconverter (class<t>), where T is a subclass of R.

Consider the following converterfactory--stringtoenum:

Package Org.springframework.core.convert.support;final class Stringtoenumconverterfactory implements Converterfactory<string, enum> {public<t extends enum> converter<string, t> getConverter (Class<T > TargetType) {return new Stringtoenumconverter (TargetType);} Private Final class Stringtoenumconverter<t extends enum> implements Converter<string, t> {private class< T> enumtype;public stringtoenumconverter (class<t> enumtype) {this.enumtype = EnumType;} Public T convert (String source) {return (T) enum.valueof (This.enumtype, Source.trim ());}}}

Genericconverter (Generic Converter)

When you need a complex converter implementation, you can consider the Genericconverter interface. It has a relatively weak type but a more flexible method header, and Genericconverter supports conversions of multiple primitive types and target types. In addition, when you implement your conversion logic, Genericconverter also allows you to use the context of the original field and the Target field. This context allows the property to be ( Field annotation-driven type conversions, or type conversions that are defined by generic information:

Package Org.springframework.core.convert.converter;public interface Genericconverter {public Set<convertiblepair > Getconvertibletypes (); object convert (object source, TypeDescriptor sourcetype, TypeDescriptor targetType);}

When implementing a Genericconverter interface, Getconvertibletypes () You need to return the supported source type and the target type of pairing (Translator Note: This method will be cached after Conversionservicefactory's registerconverters call), convert (Object, The TypeDescriptor, TypeDescriptor) method is used to define your transformation logic. The source TypeDescriptor provides access to the source field and contains the original value that needs to be converted. The target TypeDescriptor, however, provides access to the target field and is used to place the converted value.

A more typical example of Genericconverter is the conversion between the Java array type and the collection type. This arraytocollectionconverter determines the element type of the collection by introspective the fields of the target collection type. This allows each element in the source array to be converted to a collection element type before the collection is set to the Target field.

Note: since Genericconverter is a more complex SPI interface, use it only when you need it. For basic type conversions, use converter or converterfactory as a priority.


Genericconverter with conditions

Sometimes you just want to perform a converter when a certain condition is met. For example, a converter is executed only if there is a specific annotation on the target attribute, or a converter is executed when a specific method, such as a static valueof method, is defined in the target class. Then you can use Conditionalgenericconverter, which is the Genericconverter subinterface that allows you to define the matching criteria that you just mentioned:

Public interface Conditionalgenericconverter extends Genericconverter {boolean matches (TypeDescriptor sourcetype, TypeDescriptor targetType);}

A typical example of Conditionalgenericconverter is Entityconverter. It provides a durable entity identifier and a conversion between an entity reference. Such entityconverter may only match target entities that define a static Finder method (such as Findaccount (Long)). You need to check for the existence of such a finder method when implementing the matches (Typedescriptor,typedescriptor) method.

(Translator Note: The matches method is called when a type conversion is needed for the first time, and then it is cached)


Conversionservice API

Conversionservice defines a unified API for run-time execution type conversion logic. Converters usually runs after this layer façade interface:

Package Org.springframework.core.convert;public Interface Conversionservice {boolean Canconvert (class<?> SourceType, class<?> targetType);<t> T convert (Object source, class<t> TargetType); boolean Canconvert (TypeDescriptor sourcetype, TypeDescriptor targetType); object convert (object source, TypeDescriptor SourceType, TypeDescriptor targetType);}

Most Conversionservice implementation classes also implement the Converterregistry interface. Converterregistry provides an SPI for registered converters. In fact, the logic of type conversion is delegated to the registered converters in the Conversionservice implementation.

The Core.convert.support package provides a robust conversionservice implementation. Genericconversionservice, as a generic implementation class, can satisfy most situations. Conversionservicefactory provides a convenient factory for creating commonly used conversionservice configurations.

Configuring a Conversionservice

Conversionservice is a stateless object that is designed to be instantiated when the app is started and shared among multiple threads. In a typical case in a spring application, a Conversionservice instance is configured for each spring container (or applicationcontext). This conversionservice will survive in spring and be used when a type conversion is required. You can also inject it into your beans and call it directly.

Note: If Conversionservice is not registered in spring, it will use the original PropertyEditor-based system.

In order to register a default conversionservice in spring, add the following bean definition and set its ID to Conversionservice:

<bean id= "Conversionservice" class= "Org.springframework.context.support.ConversionServiceFactoryBean"/>

The default Conversionservcice can convert strings, number, enums, collections, maps, and other common types. By setting the Converters property, you can supplement or overwrite the default converters with your custom converters. The value of this converters property must be implemented converter, converterfactory, or Genericconverter interfaces.

<bean id= "Conversionservice" class= "Org.springframework.context.support.ConversionServiceFactoryBean" >< Property name= "Converters" ><list><bean class= "example. Mycustomconverter "/></list></property></bean>

It is also common to use Conversionservice in spring MVC applications. Read the section "Configuringformatting in Spring MVC" For more details on how to use <mvc:annotation-driven/>.

In some scenarios you might want to apply formatting to a type conversion. Read the section "Formatterregistry SPI" to get more information on using Formattingconversionservicefactorybean.


Using a programmatic Conversionservice

Using a programmatic Conversionservice instance, you just need to inject a conversionservice reference, just as you would inject another bean:

@Servicepublic class MyService {@Autowiredpublic MyService (Conversionservice conversionservice) { This.conversionservice = Conversionservice;} public void DoIt () {This.conversionService.convert (...)}}


6.5 Spring3 type Conversion

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.