By default DataBinder uses PropertyEditors for binding process but it can be configured with a conversion service for property values conversion.
Example
Following example shows DataBinder using a custom converter (DateToLocalDateTimeConverter) registered with DefaultConversionService.
package com.logicbig.example;
import java.time.LocalDateTime;
public class MyObject {
private LocalDateTime date;
.............
}
package com.logicbig.example;
import org.springframework.core.convert.converter.Converter;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateToLocalDateTimeConverter
implements Converter<Date, LocalDateTime> {
@Override
public LocalDateTime convert(Date source) {
return LocalDateTime.ofInstant(source.toInstant(),
ZoneId.systemDefault());
}
}
package com.logicbig.example;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.validation.DataBinder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class ConversionServiceWithDataBinderExample {
public static void main (String[] args) throws ParseException {
MutablePropertyValues mpv = new MutablePropertyValues();
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a")
.parse("01/20/2022 00:00:00 AM");
mpv.add("date", date);
DataBinder dataBinder = new DataBinder(new MyObject());
DefaultConversionService service = new DefaultConversionService();
service.addConverter(new DateToLocalDateTimeConverter());
//commenting the following line will not populate date field
dataBinder.setConversionService(service);
dataBinder.bind(mpv);
dataBinder.getBindingResult()
.getModel()
.entrySet()
.forEach(System.out::println);
}
}