博客
关于我
28-springMvc注解开发-类型转换器
阅读量:243 次
发布时间:2019-03-01

本文共 2276 字,大约阅读时间需要 7 分钟。

文章目录

实现数据类型转换

1 Converter接口

@FunctionalInterfacepublic interface Converter
{ /** 提供类型转换的逻辑 */ @Nullable T convert(S source);}

2 案例

之前通过InitBinder和DateTimeFormat注解实现过字符串转date,现在也可以通过Converter实现该功能

package study.wyy.spring.anno.web.convert;import org.springframework.core.convert.converter.Converter;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;/** * @author by wyaoyao * @Description * @Date 2021/2/15 7:49 下午 */@Componentpublic class String2DateConverter implements Converter
{ @Override public Date convert(String source) { //1.判断来源是否有值 if (StringUtils.isEmpty(source)) { throw new NullPointerException("Source can not be null!"); } try{ //2.定义转换器 DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); //3.转换并返回 return format.parse(source); }catch (Exception e){ e.printStackTrace(); } return null; }}

注册

package study.wyy.spring.anno.web.advice;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.convert.ConversionService;import org.springframework.core.convert.converter.Converter;import org.springframework.core.convert.support.GenericConversionService;import org.springframework.format.datetime.DateFormatter;import org.springframework.web.bind.WebDataBinder;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.InitBinder;@ControllerAdvicepublic class DataFormatAdvice {       @Autowired    private Converter stringToDateConverter;    @InitBinder    public void dateBinder(WebDataBinder dataBinder){           //1.获取转换服务对象        ConversionService conversionService = dataBinder.getConversionService();        //2.判断conversionService是否为GenericConversionService类型        if(conversionService instanceof GenericConversionService){               //3.强转            GenericConversionService genericConversionService = (GenericConversionService)conversionService;            //4.添加类型转换器            genericConversionService.addConverter(stringToDateConverter);        }    }}

转载地址:http://msrv.baihongyu.com/

你可能感兴趣的文章
MySQL5.6的zip包安装教程
查看>>
mysql5.7 for windows_MySQL 5.7 for Windows 解压缩版配置安装
查看>>
Webpack 基本环境搭建
查看>>
mysql5.7 安装版 表不能输入汉字解决方案
查看>>
MySQL5.7.18主从复制搭建(一主一从)
查看>>
MySQL5.7.19-win64安装启动
查看>>
mysql5.7.19安装图解_mysql5.7.19 winx64解压缩版安装配置教程
查看>>
MySQL5.7.37windows解压版的安装使用
查看>>
mysql5.7免费下载地址
查看>>
mysql5.7命令总结
查看>>
mysql5.7安装
查看>>
mysql5.7性能调优my.ini
查看>>
MySQL5.7新增Performance Schema表
查看>>
Mysql5.7深入学习 1.MySQL 5.7 中的新增功能
查看>>
Webpack 之 basic chunk graph
查看>>
Mysql5.7版本单机版my.cnf配置文件
查看>>
mysql5.7的安装和Navicat的安装
查看>>
mysql5.7示例数据库_Linux MySQL5.7多实例数据库配置
查看>>
Mysql8 数据库安装及主从配置 | Spring Cloud 2
查看>>
mysql8 配置文件配置group 问题 sql语句group不能使用报错解决 mysql8.X版本的my.cnf配置文件 my.cnf文件 能够使用的my.cnf配置文件
查看>>