Spring 3 introduced a new type conversion mechanism as an alternative to PropertyEditors.
The disadvantage of JavaBean PropertyEditor is that they are not thread-safe because they directly attempt to modify the JavaBean fields (the instance variables). JavaBeans PropertyEditor was originally designed to be used in single-threaded GUI applications.
A ConversionService is a stateless object so is thread-safe.
Spring provides built in default converters which can do conversion between strings, numbers, enums, collections, maps, and other common types.
In this tutorial we are going to learn the basic use of ConversionService.
Definition of ConversionService(Version: spring-framework 6.1.2) package org.springframework.core.convert;
........
public interface ConversionService {
boolean canConvert(@Nullable Class<?> sourceType, Class<?> targetType); 1
boolean canConvert(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType); 2
@Nullable
<T> T convert(@Nullable Object source, Class<T> targetType); 3
@Nullable
default Object convert(@Nullable Object source, TypeDescriptor targetType) {
return convert(source, TypeDescriptor.forObject(source), targetType);
} 4
@Nullable
Object convert(
@Nullable Object source,
@Nullable TypeDescriptor sourceType,
TypeDescriptor targetType); 5
}
ConversionServices basic example
Following example shows a standalone use of ConversionService .
DefaultConversionService is an implementation of ConversionService which registers many converters by default.
package com.logicbig.example;
import org.springframework.core.convert.support.DefaultConversionService;
import java.util.Collection;
import java.util.Currency;
public class ConversionServiceExample {
public static void main (String[] args) {
DefaultConversionService service = new DefaultConversionService();
Currency convert = service.convert("USD", Currency.class);
System.out.println(convert);
Collection<String> list = service.convert("Deb, Mike, Kim",
Collection.class);
System.out.println(list);
}
}
OutputUSD [Deb, Mike, Kim]
Converter interface
ConversionService uses various implementations of Converter interfaces to perform conversion.
Definition of Converter(Version: spring-framework 6.1.2) package org.springframework.core.convert.converter;
........
@FunctionalInterface
public interface Converter<S, T> {
@Nullable
T convert(S source); 1
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
Assert.notNull(after, "'after' Converter must not be null");
return (S s) -> {
T initialResult = convert(s);
return (initialResult != null ? after.convert(initialResult) : null);
};
} 2
}
In next tutorials we will go through various examples to understand ConversionService.
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 4.2.0.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|