资讯专栏INFORMATION COLUMN

spring boot 随笔 -- 配置全局的String转Date参数转换器

XBaron / 328人阅读

摘要:你在写接口的时候难免会遇到接收类型的日期参数例如转换成类型情况。

你在写接口的时候难免会遇到接收String类型的日期参数(例如:2018-04-21 11:57:36)转换成Date类型情况。
百度了一番,发现大多数答案都是这样子的:

@Configuration
public class WebConfigBeans {

    @Autowired
    RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void initEditableValidation(){
       ConfigurableWebBindingInitializer configurableWebBindingInitializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if(configurableWebBindingInitializer.getConversionService()!=null){
            GenericConversionService service = (GenericConversionService) configurableWebBindingInitializer.getConversionService();
            service.addConverter(new StringToDateConverter());
        }
    }
}

上面的代码确实解决了问题,可是,代码有点不绿色节能。

以下是我的实现:
配置配置全局的String转Date参数转换器,可以简单解决这个问题!

web配置如下(spring boot 1.x 2.x 通用):

@Configuration
public class SpringMVCConfig extends WebMvcConfigurationSupport{

    /**
     * 添加自定义的Converters和Formatters.
     */
    @Override
    protected void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConverter());
    }
}

绿色环保更节能!

String转Date转换器实现如下(好吧,我承认下面的代码这是我抄来的):

public class StringToDateConverter implements Converter {

    
     private static final String dateFormat      = "yyyy-MM-dd HH:mm:ss";
     private static final String shortDateFormat = "yyyy-MM-dd";

        @Override
        public Date convert(String source) {
            if (StringUtils.isBlank(source)) {
                return null;
            }
            source = source.trim();
            try {
                if (source.contains("-")) {
                    SimpleDateFormat formatter;
                    if (source.contains(":")) {
                        formatter = new SimpleDateFormat(dateFormat);
                    } else {
                        formatter = new SimpleDateFormat(shortDateFormat);
                    }
                    return formatter.parse(source);
                } else if (source.matches("^d+$")) {
                    Long lDate = new Long(source);
                    return new Date(lDate);
                }
            } catch (Exception e) {
                throw new RuntimeException(String.format("parser %s to Date fail", source));
            }
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69419.html

相关文章

  • ControllerAdvice拦截器

    摘要:看成提供的一个特殊的拦截器。是一个,用于定义最主要用途,和方法,适用于所有使用方法拦截。为所有封装统一异常处理代码。为所有设置全局变量。用于为所有设置某个类型的数据转换器。 Spring3.2开始提供的新注解,控制器增强(AOP),最主要的应用是做统一的异常处理。@ControllerAdvice(看成spring mvc提供的一个特殊的拦截器)。@ControllerAdvice是一...

    caohaoyu 评论0 收藏0
  • 慕课网_《SpringBoot开发常用技术整合》学习总结

    摘要:时间年月日星期四说明本文部分内容均来自慕课网。哈希表实现命令,将哈希表中的域的值设为实现命令,返回哈希表中给定域的值实现命令,删除哈希表中的一个或多个指定域,不存在的域将被忽略。实现命令,返回哈希表中,所有的域和值。 时间:2018年04月19日星期四说明:本文部分内容均来自慕课网。@慕课网:https://www.imooc.com教学源码:https://github.com/zc...

    chengtao1633 评论0 收藏0
  • Spring Boot属性绑定

    摘要:所以适合简单属性值的获取,不知何复杂对象的绑定。绑定对象绑定绑定列表转换以及默认值绑定过程回调函数,高度定制绑定开始绑定成功绑定失败没有找到匹配的属性绑定结束 Spring Boot中的属性绑定 之前翻译了一篇不怎么样的文章,主要是翻译的水平有限,自己翻译的云里雾里,发现平时只会有@ConfigurationProperties注解,对SpringBoot强大的属性绑定知之甚少,所以以...

    xfee 评论0 收藏0
  • ★推荐一款适用于SpringBoot项目轻量级HTTP客户端框架

    摘要:请求重试拦截器错误解码器在发生请求错误包括发生异常或者响应数据不符合预期的时候,错误解码器可将相关信息解码到自定义异常中。 在SpringBoot项目直接使用okhttp、httpClient或者RestTemplate发起HTTP请求,既繁琐又不方便统一管理。因此,在这里推荐一个适...

    不知名网友 评论0 收藏0
  • Spring Boot - 整合Jsp/FreeMarker

    摘要:大家自己了解一下的使用方法,我这里就不进行详细的讲述了。启动方式两种方式都可以主函数启动或者验证访问页面,验证是否输出了当前时间。为了提高大家学习效果,录制了同步的视频课程,还望大家支持视频课程 Spring Boot - 初识 Hello World 索引 Spring Boot - 初识 Hello World Spring Boot - Servlet、过滤器、监听器、拦截器 ...

    AbnerMing 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<