问题描述
我使用 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());
}
}
希望这可行.
这篇关于如何在 Spring Boot 中注册自定义转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)