如题,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);
}
}
}
}