已配置Date转Timestamp转换器仍遇ConverterNotFoundException求助
我实现了一个将java.util.Date转换为java.sql.Timestamp的Converter接口实现类DateToTimestampConverter,代码如下:
package com.application.applicationService.common; import org.jetbrains.annotations.NotNull; import org.springframework.core.convert.converter.Converter; import java.util.Date; import java.sql.Timestamp; public class DateToTimestampConverter implements Converter<Date, Timestamp> { @Override public Timestamp convert(@NotNull Date date) { return new Timestamp(date.getTime()); } }
我先尝试给该类添加@Component注解但未解决问题,之后又通过实现WebMvcConfigurer的配置类注册转换器,代码如下:
package com.application.applicationService.config; import com.application.applicationService.common.DateToTimestampConverter; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new DateToTimestampConverter()); } }
但依然抛出以下错误:
2024-06-18T18:56:38.033+05:30 ERROR 7676 --- [applicationService] [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.util.Date] to type [java.sql.Timestamp]
检查转换器注册的上下文范围
Spring MVC的WebMvcConfigurer.addFormatters注册的转换器仅作用于Web请求参数绑定、响应序列化场景。如果转换发生在ORM框架映射、Service层内部等其他上下文,该转换器不会生效:- 若为JPA/Hibernate场景:需注册
AttributeConverter而非Spring的Converter,或在实体类字段上显式处理转换逻辑; - 若为Service层或Bean间转换:需注册到全局
ConversionService,可通过@Configuration类注入ConversionServiceFactoryBean添加转换器:@Configuration public class ConversionConfig { @Bean public ConversionService conversionService() { ConversionServiceFactoryBean factory = new ConversionServiceFactoryBean(); factory.setConverters(Set.of(new DateToTimestampConverter())); factory.afterPropertiesSet(); return factory.getObject(); } }
- 若为JPA/Hibernate场景:需注册
验证泛型类型匹配
确认实际需要转换的Date类型确实是java.util.Date,而非其子类(如java.sql.Date)。如果是java.sql.Date转java.sql.Timestamp,需新增对应转换器并注册:public class SqlDateToTimestampConverter implements Converter<java.sql.Date, Timestamp> { @Override public Timestamp convert(@NotNull java.sql.Date date) { return new Timestamp(date.getTime()); } }确认配置类被Spring扫描
检查WebMvcConfig所在的com.application.applicationService.config包是否在Spring Boot组件扫描范围内,可在启动类添加@ComponentScan(basePackages = "com.application.applicationService")显式指定扫描路径,避免配置类未加载。排查转换器冲突
若项目中存在其他自定义ConversionService配置,可能覆盖默认Spring MVC转换服务,需检查其他WebMvcConfigurer实现类,确保所有转换器都被正确添加。临时应急方案
若以上方法无法快速生效,可在转换发生的代码处直接调用转换逻辑:Timestamp timestamp = new Timestamp(utilDate.getTime());
内容的提问来源于stack exchange,提问作者sohamsk

