如何在spring boot 1.4.1-RELEASE中设置针织物以将日期转换为ISO 8601?

时间:2016-10-25 22:52:44

标签: spring-boot jersey-2.0 iso8601

在Spring boot 1.3.6-RELEASE中我将以下类注册到了jersey。每个java.util.Date字段都将被读取并以ISO8601格式返回。但是,当更新到1.4.1-RELEASE时,它现在有时会起作用,有时却不起作用。启用此功能的新方法是什么?

package com.mypackage;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.Date;

import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.util.ISO8601Utils;

@Provider
public class DateTimeParamConverterProvider implements ParamConverterProvider {

    @SuppressWarnings("unchecked")
    @Override
    public <T> ParamConverter<T> getConverter(Class<T> clazz, Type type, Annotation[] annotations) {
        if (type.equals(Date.class)) {
            return (ParamConverter<T>) new DateTimeParamConverter();
        } else {
            return null;
        }
    }

    static class DateTimeParamConverter implements ParamConverter<Date> {
        @Override
        public java.util.Date fromString(String value) {
            if (value == null) {
                return null;
            }
            try {
                return ISO8601Utils.parse(value, new ParsePosition(0));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String toString(Date value) {
            return ISO8601Utils.format(value);
        }
    }
}

我像这样注册这个提供者:

@Component
@ApplicationPath("/")
public class JerseyConfiguration extends ResourceConfig {
    private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName());

    @Autowired
    public JerseyConfiguration(LogRequestFilter lrf) {
        register(new ObjectMapperContextResolverNonNull());
        register(RestServiceImpl.class);
        property(ServletProperties.FILTER_FORWARD_ON_404, true);
        register(DateTimeParamConverterProvider.class, 6000);
...

1 个答案:

答案 0 :(得分:1)

只需在application.properties中定义:

spring.jackson.date-format=com.fasterxml.jackson.databind.util.ISO8601DateFormat