How to register custom converters in spring boot?

2019-01-25 09:23发布

I writing application using spring-boot-starter-jdbc (v1.3.0).

The problem that I met: Instance of BeanPropertyRowMapper fails as it cannot convert from java.sql.Timestamp to java.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 for BeanPropertyRowMapper.

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.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-25 10:25

I suggest to use @Autowired and the related dependency injection mechanism of spring to use a single ConversionService instance throughout your application. The ConversionService will be instantiated within the configuration.

All Converters to be available application wide receive an annotation (e.g. @AutoRegistered). On application start a @Component FormatterRegistrar (Type name itself is a bit misleading, yes it is "...Registrar" as it does the registering. And @Component as it is fully spring managed and requires dependency injection) will receive @AutoRegistered List of all annotated Converters.

See this thread for concrete implementation details. We use this mechanism within our project and it works out like a charm.

查看更多
登录 后发表回答