Spring MVC Controller返回json日期格式配置失效的解决办法

如题,Spring MVC 4.3.0版本,配置jackson读写json。Controller层方法返回值对象包含java.util.Date类型的属性,并且在applicationContext.xml中配置了jackson的日期格式:

XML 复制代码
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!--                <property name="objectMapper" ref="objectMapper"/>-->
                <constructor-arg index="0" ref="objectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
        <property name="simpleDateFormat" value="yyyy-MM-dd HH:mm:ss"/>
    </bean>

但是调用Controller层方法发现日期格式返回的是时间戳,日期格式配置失效了。

经过多次调试跟踪,笔者发现原因是<mvc:annotation-driven>标签会自动注册RequestMappingHandlerAdapter(位置在WebMvcConfigurationSupport类中),其中setMessageConverters方法会覆盖掉我们配置的jackson converter,因此问题的解决从Spring容器中获取RequestMappingHandlerAdapter这个bean,然后找到内部的MappingJackson2HttpMessageConverter,以代码的方式重新配置即可。

java 复制代码
@Configuration
//@EnableWebMvc
public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {

    private final Logger logger = LoggerFactory.getLogger(MyWebMvcConfigurer.class);

    @Autowired
    private RequestMappingHandlerAdapter adapter;

    @PostConstruct
    public void configureAdapter() {
        for(HttpMessageConverter<?> converter: adapter.getMessageConverters()) {
            if(converter instanceof MappingJackson2HttpMessageConverter) {
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                ((MappingJackson2HttpMessageConverter) converter).setObjectMapper(objectMapper);
            }
        }
    }
}
相关推荐
派大鑫wink9 分钟前
【Day42】SpringMVC 入门:DispatcherServlet 与请求映射
java·开发语言·mvc
WZTTMoon30 分钟前
Spring Boot 为何不推荐使用@Autowired
java·spring boot·spring
忠实米线36 分钟前
使用lottie.js播放json动画文件
开发语言·javascript·json
若鱼191938 分钟前
SpringBoot4.0新特性-声明式HTTP远程调用客户端
java·spring
鱼跃鹰飞1 小时前
面试题:说一下Spring的事务传播特性
java·数据库·spring
invicinble1 小时前
关于spring的全量认识
java·spring
魔芋红茶11 小时前
Spring Security 学习笔记 2:架构
笔记·学习·spring
卓怡学长13 小时前
m115乐购游戏商城系统
java·前端·数据库·spring boot·spring·游戏
Remember_99317 小时前
【数据结构】深入理解优先级队列与堆:从原理到应用
java·数据结构·算法·spring·leetcode·maven·哈希算法
热爱学习的小翁同学17 小时前
SharePoint 列格式化 JSON 配置
json·sharepoint