spring boot 配置全局日期类型转换器

2018-09-18 06:36:24来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1. 首先自定义一个类型转换器

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyDataConvert implements Converter<String, Date> {
  //这里可以自己灵活变通
    private String [] pattern = {"yyyy-MM-dd","yyyy年MM月dd日"};
    @Override
    public Date convert(String s) {
        System.out.println("convert");
        for (int i=0;i<pattern.length;i++){
            try {
                return  new SimpleDateFormat(pattern[i]).parse(s);
            } catch (ParseException e) {
                continue;
            }
        }
        return null;
    }
}

2.在配置类中注册自定义类型转换器

import com.example.demo.convert.MyDataConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

import javax.annotation.PostConstruct;

@Configuration
public class WebConfigurer extends WebMvcConfigurationSupport  {

    @Autowired
    private RequestMappingHandlerAdapter handlerAdapter;

    @PostConstruct
    public void initEditableAvlidation() {

        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)handlerAdapter.getWebBindingInitializer();
        if(initializer.getConversionService()!=null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            genericConversionService.addConverter(new MyDataConvert());//添加自定义的类型转换器
        }
    }


}

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:学员会诊之02:SVN协作以及Page类的设计

下一篇:SQL like 模糊查询, in