如何在 Spring Boot 中注册自定义转换器?

2022-01-18 00:00:00 spring java spring-boot spring-data

我使用 spring-boot-starter-jdbc (v1.3.0) 编写应用程序.

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

我遇到的问题:BeanPropertyRowMapper 的实例失败,因为它无法从 java.sql.Timestamp 转换为 java.time.LocalDateTime.

The problem that I met: Instance of BeanPropertyRowMapper fails as it cannot convert from java.sql.Timestamp to java.time.LocalDateTime.

为了复制这个问题,我实现了org.springframework.core.convert.converter.Converter 用于这些类型.

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();
    }
}

我的问题是:如何为 BeanPropertyRowMapper 提供 TimeStampToLocalDateTimeConverter.

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?

以下代码将我们带到初始化阶段的NullPointerException:

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();
}    

谢谢.

推荐答案

所有自定义转换服务都必须注册到 FormatterRegistry.尝试通过实现 WebMvcConfigurer 来创建新配置并注册转换服务

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());
    }
}

希望这可行.

相关文章