1

我正在开发一个使用纯 Java 配置来设置其 bean 的 Spring WebMvc(不是 Spring Boot)项目。我很难让 Spring/Jackson 尊重带有 java.time (jsr310) 对象(如 LocalDateTime)的 @DateTimeFormat 注释。

我在类路径上有 jackson-datatype-jsr310 和 jackson-databind jar(版本 2.7.4),以及基本 webmvc 应用程序 spring-context 和 spring-webmvc(版本 4.3.0.RELEASE)的相关 spring jar

这是我的相关配置类:

@Configuration
@ComponentScan({"com.example.myapp"})
public class WebAppConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper mapper = Jackson2ObjectMapperBuilder
            .json()
            .indentOutput(true)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .build();

        converters.add(new MappingJackson2HttpMessageConverter(mapper));

        super.addDefaultHttpMessageConverters(converters);
    }
}

我已经通过在休息控制器上序列化我的数据模型对此进行了测试。似乎杰克逊尊重@JsonFormat,但完全忽略了@DateTimeFormat。

为了让 spring/jackson 尊重@DateTimeFormat,我还缺少什么额外的配置?我应该注意的两个注释之间是否有任何关键区别,仅使用@JsonFormat 可能会遇到的问题?

4

1 回答 1

2

@JsonFormat是杰克逊注解;@DateTimeFormat是一个 Spring 注解。

@JsonFormatLocalDateTime将在序列化为JSON期间控制格式。

Jackson 不知道 Spring 的@DateTimeFormat,当它在 JSP 视图中呈现时,它用于控制 Spring 中 bean 的格式。

Java文档:

http://docs.spring.io/spring-framework/docs/4.2.3.RELEASE/javadoc-api/org/springframework/format/annotation/DateTimeFormat.html

http://static.javadoc.io/com.fasterxml.jackson.core/jackson-annotations/2.7.5/com/fasterxml/jackson/annotation/JsonFormat.html

于 2016-06-17T02:19:20.213 回答