This tutorial shows how to create a custom converter and register with ConversionService.
Example
In this example we are going to create a custom converter to convert String to java.time.LocalDateTime.
Implementing Converter interface
package com.logicbig.example;
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class StringToLocalDateConverter
implements Converter<String, LocalDate> {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
@Override
public LocalDate convert(String dateTimeString) {
return LocalDate.parse(dateTimeString, formatter);
}
}
Registering our converter
Besides implementing ConversionService, DefaultConversionService also implements ConverterRegistry interface which is an abstraction of converters registration with the underlying conversion service. In following configuration we are registering our custom converter with DefaultConversionService
package com.logicbig.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
@Configuration
public class Config {
@Bean
public ConversionService conversionService() {
DefaultConversionService service = new DefaultConversionService();
service.addConverter(new StringToLocalDateConverter());
return service;
}
@Bean
public ClientBean clientBean() {
return new ClientBean("2010/10/05");
}
}
Client code using ConversionService
public class ClientBean {
private final String date;
@Autowired
private ConversionService conversionService;
ClientBean(String date) {
this.date = date;
}
public void showLocalDateTime() {
LocalDate localDate = conversionService.convert(date, LocalDate.class);
System.out.println(localDate);
}
}
Main class
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class CustomConverterExample {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(
Config.class);
ClientBean clientBean = context.getBean(ClientBean.class);
clientBean.showLocalDateTime();
}
}
Output2010-10-05
Example ProjectDependencies and Technologies Used: - spring-context 6.1.2 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.1.2 Version compatibilities of spring-context with this example: Versions in green have been tested.
- JDK 17
- Maven 3.8.1
|