记录Feign调用时对LocalDateTime的处理
feign api调用参数类型为LocalDateTime一直报错,类型转换错误
简单记录一下解决方式吧
调用方
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; @Configuration public class LocalDateTimeConfig { @Bean(name = "mapperObject") public ObjectMapper getObjectMapper() { return new ObjectMapper().registerModule(new ParameterNamesModule()).registerModule(new Jdk8Module()) .registerModule(new JavaTimeModule()); } }
服务提供方
import java.time.LocalDateTime; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; @Configuration public class WebConfigBeans { @Autowired private RequestMappingHandlerAdapter handlerAdapter; @PostConstruct public void initEditableValidation() { ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter .getWebBindingInitializer(); if (initializer.getConversionService() != null) { GenericConversionService genericConversionService = (GenericConversionService) initializer .getConversionService(); genericConversionService.addConverter(String.class, LocalDateTime.class, new String2DateConverter()); } } }
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import org.springframework.core.convert.converter.Converter; public class DateConverter implements Converter<String, LocalDateTime> { @Override public LocalDateTime convert(String source) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return LocalDateTime.parse(source,formatter); } }