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);
            }
        }
    }
}
相关推荐
一路向北North9 小时前
Spring Security OAuth2.0(20):完善环境配置
java·后端·spring
9523613 小时前
Redis - 基本操作
数据库·redis·spring·缓存
卓怡学长13 小时前
w261springboot基于web学校课程管理系统
java·数据库·spring boot·spring·intellij-idea
她说..14 小时前
Apache Commons Lang3 Pair 完整版实战详解
java·spring·java-ee·apache·springboot
黒亱中旳1 天前
Java AI 框架三国杀:Solon AI vs Spring AI vs LangChain4j 深度对比
java·人工智能·spring
恼书:-(空寄1 天前
Spring AOP底层是怎么织入的?——ProxyFactory、JDK Proxy vs CGLIB与编译期织入
spring·动态代理
长不胖的路人甲1 天前
SpringCloud 服务雪崩、熔断、降级
后端·spring·spring cloud
卓怡学长1 天前
w263基于springboot + vue 健康饮食管理系统
java·数据库·vue.js·spring boot·spring·intellij-idea
KINGSEA_1681 天前
Spring事务原理与高频考点
spring
Y001112362 天前
SpringBoot 基础篇
java·spring boot·spring