How to register custom converters in spring boot?
All custom conversion service has to be registered with the FormatterRegistry. Try creating a new configuration and register the conversion service by implementing the WebMvcConfigurer
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addallFormatters(FormatterRegistry registry) {
registry.addConverter(new TimeStampToLocalDateTimeConverter());
}
}
Hope this works.
Admin
Updated on June 11, 2022Comments
-
Admin almost 2 years
I writing application using spring-boot-starter-jdbc (v1.3.0).
The problem that I met: Instance of
BeanPropertyRowMapper
fails as it cannot convert fromjava.sql.Timestamp
tojava.time.LocalDateTime
.In order to copy this problem, I implemented
org.springframework.core.convert.converter.Converter
for these types.public class TimeStampToLocalDateTimeConverter implements Converter<Timestamp, LocalDateTime> { @Override public LocalDateTime convert(Timestamp s) { return s.toLocalDateTime(); } }
My question is: How do I make available
TimeStampToLocalDateTimeConverter
forBeanPropertyRowMapper
.More general question, how do I register my converters, in order to make them available system wide?
The following code bring us to
NullPointerException
on initialization stage:private Set<Converter> getConverters() { Set<Converter> converters = new HashSet<Converter>(); converters.add(new TimeStampToLocalDateTimeConverter()); converters.add(new LocalDateTimeToTimestampConverter()); return converters; } @Bean(name="conversionService") public ConversionService getConversionService() { ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean(); bean.setConverters(getConverters()); bean.afterPropertiesSet(); return bean.getObject(); }
Thank you.
-
Frans over 3 yearsThe question was about Spring (core) converters, not JPA converters.
-
PravyNandas almost 3 years``` Thanks. But the method name should be addFormatters() ```
-
Frans almost 2 yearsThis only works in a WebMVC context. The question asker specifically asked to be able to use the convert system-wide. This does not accomplish that.
-
Frans almost 2 yearsThis only works in a WebMVC context. The question asker specifically asked to be able to use the convert system-wide. This does not accomplish that.