spring boot 注册类型转换 (转载)

spring boot注册一个全局的类型转换器,转换表单中的String 到Date

@Configuration
public class WebConfig {

    @Autowired
    private RequestMappingHandlerAdapter requestMappingHandlerAdapter;

    @PostConstruct
    public void addConversionConfig() {
        ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) requestMappingHandlerAdapter.getWebBindingInitializer();
        if (initializer.getConversionService() != null) {
            GenericConversionService genericConversionService = (GenericConversionService)initializer.getConversionService();
            genericConversionService.addConverter(new StringToDateConverter());
        }
    }
}

类StringToDateConverter要实现Converter

public class StringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        Assert.hasText(source, "Null or empty date string");
        Date date = DateUtil.parseDate(source, DateUtil.DATE_FORMAT_MILLISECOND);
        return date;
    }
}

时间工具类

public class DateUtil {
    public final static String DATE_FORMAT_DAY = "yyyy-MM-dd";
    public final static String DATE_FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss";
    public final static String DATE_FORMAT_MILLISECOND = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

    public static Date parseDate(String dateString, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            throw new CustomerException(HttpStatus.ERROR, "时间格式错误");
        }
    }
}

本文转载自http://www.wang1314.com/doc/topic-1335513-1.html

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页