乐趣区

关于java:Spring-Boot-别再用-Date-作为入参了LocalDateTimeLocalDate-真香

作者:TinyThing
链接:https://www.jianshu.com/p/b52db905f020

0x0 背景

我的项目中应用 LocalDateTime 系列作为 dto 中工夫的类型,然而 spring 收到参数后总报错,为了全局配置工夫类型转换,尝试了如下 3 中办法。

注:本文基于 Springboot2.0 测试,如果无奈失效可能是 spring 版本较低导致的。PS:如果你的 Controller 中的 LocalDate 类型的参数啥注解(RequestParam、PathVariable 等)都没加,也是会出错的,因为默认状况下,解析这种参数应用 ModelAttributeMethodProcessor 进行解决,而这个处理器要通过反射实例化一个对象进去,而后再对对象中的各个参数进行 convert,然而 LocalDate 类没有构造函数,无奈反射实例化因而会报错!!!

0x1 当 LocalDateTime 作为 RequestParam 或者 PathVariable 时

这种状况要和工夫作为 Json 字符串时区别对待,因为前端 json 转后端 pojo 底层应用的是 Json 序列化 Jackson 工具(HttpMessgeConverter);而工夫字符串作为一般申请参数传入时,转换用的是 Converter,两者有区别哦。
在这种状况下,有如下几种计划:

举荐一个开源收费的 Spring Boot 实战我的项目:

https://github.com/javastacks/spring-boot-best-practice

1. 应用 Converter

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.HttpMessageConverter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Configuration
public class DateConfig {

    @Bean
    public Converter<String, LocalDate> localDateConverter() {return new Converter<>() {
            @Override
            public LocalDate convert(String source) {return LocalDate.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }
        };
    }

    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<>() {
            @Override
            public LocalDateTime convert(String source) {return LocalDateTime.parse(source, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        };
    }

}

以上两个 bean 会注入到 spring mvc 的参数解析器(如同叫做 ParameterConversionService),当传入的字符串要转为 LocalDateTime 类时,spring 会调用该 Converter 对这个入参进行转换。

2. 应用 ControllerAdvice 配合 initBinder

@ControllerAdvice
public class GlobalExceptionHandler {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {setValue(LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
        });
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        });
        binder.registerCustomEditor(LocalTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {setValue(LocalTime.parse(text, DateTimeFormatter.ofPattern("HH:mm:ss")));
            }
        });
    }
}

从名字就可以看进去,这是在 controller 做环切(这外面还能够全局异样捕捉),在参数进入 handler 之前进行转换;转换为咱们相应的对象。

0x2 当 LocalDateTime 作为 Json 模式传入

这种状况下,如同上文形容,要利用 Jackson 的 json 序列化和反序列化来做:

@Configuration
public class JacksonConfig {

    /** 默认日期工夫格局 */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /** 默认日期格局 */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /** 默认工夫格局 */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";


    @Bean
    public ObjectMapper objectMapper(){ObjectMapper objectMapper = new ObjectMapper();
//            objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
//            objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        objectMapper.registerModule(javaTimeModule).registerModule(new ParameterNamesModule());
        return objectMapper;
    }

}

0x3 来个残缺的配置吧

Spring Boot 根底就不介绍了,举荐看这个实战我的项目:

https://github.com/javastacks/spring-boot-best-practice

package com.fly.hi.common.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Configuration
public class DateConfig {

    /** 默认日期工夫格局 */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /** 默认日期格局 */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /** 默认工夫格局 */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * LocalDate 转换器,用于转换 RequestParam 和 PathVariable 参数
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {return new Converter<>() {
            @Override
            public LocalDate convert(String source) {return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
            }
        };
    }

    /**
     * LocalDateTime 转换器,用于转换 RequestParam 和 PathVariable 参数
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {return new Converter<>() {
            @Override
            public LocalDateTime convert(String source) {return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
            }
        };
    }

    /**
     * LocalTime 转换器,用于转换 RequestParam 和 PathVariable 参数
     */
    @Bean
    public Converter<String, LocalTime> localTimeConverter() {return new Converter<>() {
            @Override
            public LocalTime convert(String source) {return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
            }
        };
    }

    /**
     * Date 转换器,用于转换 RequestParam 和 PathVariable 参数
     */
    @Bean
    public Converter<String, Date> dateConverter() {return new Converter<>() {
            @Override
            public Date convert(String source) {SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                try {return format.parse(source);
                } catch (ParseException e) {throw new RuntimeException(e);
                }
            }
        };
    }


    /**
     * Json 序列化和反序列化转换器,用于转换 Post 申请体中的 json 以及将咱们的对象序列化为返回响应的 json
     */
    @Bean
    public ObjectMapper objectMapper(){ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

        //LocalDateTime 系列序列化和反序列化模块,继承自 jsr310,咱们在这里批改了日期格局
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));


        //Date 序列化和反序列化
        javaTimeModule.addSerializer(Date.class, new JsonSerializer<>() {
            @Override
            public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String formattedDate = formatter.format(date);
                jsonGenerator.writeString(formattedDate);
            }
        });
        javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<>() {
            @Override
            public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
                String date = jsonParser.getText();
                try {return format.parse(date);
                } catch (ParseException e) {throw new RuntimeException(e);
                }
            }
        });

        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }


}

0x4 深入研究 SpringMVC 数据绑定过程

接下来进入 debug 模式,看看 mvc 是如何将咱们 request 中的参数绑定到咱们 controller 层办法入参的:

写一个简略 controller,下个断点看看办法调用栈:

@GetMapping("/getDate")
public LocalDateTime getDate(@RequestParam LocalDate date,
                             @RequestParam LocalDateTime dateTime,
                             @RequestParam Date originalDate) {System.out.println(date);
    System.out.println(dateTime);
    System.out.println(originalDate);
    return LocalDateTime.now();}

断住当前,咱们看下办法调用栈中一些要害办法:

// 进入 DispatcherServlet
doService:942, DispatcherServlet
// 解决申请
doDispatch:1038, DispatcherServlet
// 生成调用链(前解决、理论调用办法、后处理)handle:87, AbstractHandlerMethodAdapter
// 反射获取到理论调用办法,筹备开始调用
invokeHandlerMethod:895, RequestMappingHandlerAdapter
invokeAndHandle:102, ServletInvocableHandlerMethod
// 这里是要害,参数从这里开始获取到
invokeForRequest:142, InvocableHandlerMethod
doInvoke:215, InvocableHandlerMethod
// 这个是 Java reflect 调用,因而肯定是在这之前获取到的参数
invoke:566, Method

根据上述剖析,发现 invokeForRequest:142, InvocableHandlerMethod 这里的代码是用来拿到理论参数的:

@Nullable
public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
        Object... providedArgs) throws Exception {
    // 这个办法是获取参数的,在这里下个断
    Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
    if (logger.isTraceEnabled()) {logger.trace("Arguments:" + Arrays.toString(args));
    }
    // 这里开始调用办法
    return doInvoke(args);
}

进入这个办法看看是什么操作:

protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
        Object... providedArgs) throws Exception {
    // 获取办法参数数组,蕴含了入参信息,比方类型、泛型等等
    MethodParameter[] parameters = getMethodParameters();
    // 这个用来寄存一会从 request parameter 转换的参数
    Object[] args = new Object[parameters.length];
    for (int i = 0; i < parameters.length; i++) {MethodParameter parameter = parameters[i];
        parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
        // 这里看起来没啥卵用(providedArgs 为空)args[i] = resolveProvidedArgument(parameter, providedArgs);
        // 这里开始获取到办法理论调用的参数,步进
        if (this.argumentResolvers.supportsParameter(parameter)) {
            // 从名字就看进去:参数解析器解析参数
            args[i] = this.argumentResolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);
            continue;
        }
    }
    return args;
}

进入 resolveArgument 看看:

public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
    // 依据办法入参,获取对应的解析器
    HandlerMethodArgumentResolver resolver = getArgumentResolver(parameter);
     // 开始解析参数(把申请中的 parameter 转为办法的入参)return resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);
}

这里依据参数获取相应的参数解析器,看看外部如何获取的:

// 遍历,调用 supportParameter 办法,跟进看看
for (HandlerMethodArgumentResolver methodArgumentResolver : this.argumentResolvers) {if (methodArgumentResolver.supportsParameter(parameter)) {
        result = methodArgumentResolver;
        this.argumentResolverCache.put(parameter, result);
        break;
    }
}

这里,遍历参数解析器,查找有没有适宜的解析器!那么,有哪些参数解析器呢(我测试的时候有 26 个)???我列出几个重要的看看,是不是很眼生!!!

{RequestParamMethodArgumentResolver@7686} 
{PathVariableMethodArgumentResolver@8359} 
{RequestResponseBodyMethodProcessor@8366} 
{RequestPartMethodArgumentResolver@8367} 

咱们进入最罕用的一个解析器看看他的 supportsParameter 办法,发现就是通过参数注解来获取相应的解析器的。

public boolean supportsParameter(MethodParameter parameter) {
    // 如果参数领有注解 @RequestParam,则走这个分支(晓得为什么上文要对 RequestParam 和 Json 两种数据区别对待了把)if (parameter.hasParameterAnnotation(RequestParam.class)) {
        // 这个仿佛是对 Optional 类型的参数进行解决的
        if (Map.class.isAssignableFrom(parameter.nestedIfOptional().getNestedParameterType())) {RequestParam requestParam = parameter.getParameterAnnotation(RequestParam.class);
            return (requestParam != null && StringUtils.hasText(requestParam.name()));
        }
        else {return true;}
    }
    //......
}

也就是说,对于 @RequestParam@RequestBody以及 @PathVariable 注解的参数,SpringMVC 会应用不通的参数解析器进行数据绑定!
那么,这三种解析器别离应用什么 Converter 解析参数呢?咱们别离进入三种解析器看一看:
首先看下 RequestParamMethodArgumentResolver 发现外部应用 WebDataBinder 进行数据绑定,底层应用的是 ConversionService(也就是咱们的 Converter 注入的中央)

WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
// 通过 DataBinder 进行数据绑定的
arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
// 跟进 convertIfNecessary()
public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType,
        @Nullable MethodParameter methodParam) throws TypeMismatchException {return getTypeConverter().convertIfNecessary(value, requiredType, methodParam);
}
// 持续跟进,看到了把
ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
    if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
        try {return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
        }
        catch (ConversionFailedException ex) {
            // fallback to default conversion logic below
            conversionAttemptEx = ex;
        }
    }
}

而后看下 RequestResponseBodyMethodProcessor 发现应用的转换器是 HttpMessageConverter 类型的:

//resolveArgument 办法外部调用上面进行参数解析
Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());

//step into readWithMessageConverters(),咱们看到这里的 Converter 是 HttpMessageConverter
for (HttpMessageConverter<?> converter : this.messageConverters) {Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
    GenericHttpMessageConverter<?> genericConverter =
            (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
    if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
            (targetClass != null && converter.canRead(targetClass, contentType))) {if (message.hasBody()) {
            HttpInputMessage msgToUse =
                    getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
            body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
                    ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
            body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
        }
        else {body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
        }
        break;
    }
}

最初看下 PathVariableMethodArgumentResolver 发现 和 RequestParam 走的执行门路统一(二者都是继承自 AbstractNamedValueMethodArgumentResolver 解析器),因而代码就不贴了。

0xFF 总结

如果要转换 request 传来的参数到咱们指定的类型,依据入参注解要进行辨别:

  1. 如果是 RequestBody,那么通过配置 ObjectMapper(这个玩意儿会注入到 Jackson 的 HttpMessagConverter 外面,即 MappingJackson2HttpMessageConverter 中)来实现 Json 格局数据的序列化和反序列化;
  2. 如果是 RequestParam 或者 PathVariable 类型的参数,通过配置 Converter 实现参数转换(这些 Converter 会注入到 ConversionService 中)。

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿(2022 最新版)

2. 劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

退出移动版