https://blog.csdn.net/qq906627950/article/details/79503801
我整合在一个配置类里测过,可用,feign调用服务接收Date报错
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gzkj.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.gzkj.auth.client.interceptor.UserAuthRestInterceptor;
import com.gzkj.base.handler.GlobalExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.text.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
@Configuration
public class WebConfig {
@Autowired
private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;
@Bean
public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() {
ObjectMapper mapper = jackson2ObjectMapperBuilder.build();
// ObjectMapper为了保障线程安全性,里面的配置类都是一个不可变的对象
// 所以这里的setDateFormat的内部原理其实是创建了一个新的配置类
DateFormat dateFormat = mapper.getDateFormat();
mapper.setDateFormat(new MyDateFormat(dateFormat));
MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
mapper);
return mappingJsonpHttpMessageConverter;
}
class MyDateFormat extends DateFormat {
private DateFormat dateFormat;
private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
public MyDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return dateFormat.format(date, toAppendTo, fieldPosition);
}
@Override
public Date parse(String source, ParsePosition pos) {
Date date = null;
try {
date = format1.parse(source, pos);
} catch (Exception e) {
date = dateFormat.parse(source, pos);
}
return date;
}
// 主要还是装饰这个方法
@Override
public Date parse(String source) throws ParseException {
Date date = null;
try {
// 先按我的规则来
date = format1.parse(source);
} catch (Exception e) {
// 不行,那就按原先的规则吧
date = dateFormat.parse(source);
}
return date;
}
// 这里装饰clone方法的原因是因为clone方法在jackson中也有用到
@Override
public Object clone() {
Object format = dateFormat.clone();
return new MyDateFormat((DateFormat) format);
}
}
}