How to register custom converters in spring boot?(如何在 Spring Boot 中注册自定义转换器?)
问题描述
我使用 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 中注册自定义转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Spring Boot 中注册自定义转换器?
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
