springboot:扩展类型转换器

需求:提交一个字符串到后端的java.sql.Time类型,就报错了:

Failed to convert property value of type [java.lang.String] to required type [java.sql.Time]

正常提交到java.util.Date类型是没有问题的。

所以这里就需要扩展内置的springmvc的转换器

代码如下:

WebConfig : 添加新的类型转换器

import javax.annotation.PostConstruct;

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.mvc.method.annotation.RequestMappingHandlerAdapter;

import com.csget.web.converter.StringToTimeConverter;

@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 StringToTimeConverter());
    }
  }
}

StringToTimeConverter :类型转换器的具体实现

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class StringToTimeConverter implements Converter<String, Time> {
  public Time convert(String value) {
    Time time = null;
    if (StringUtils.isNotBlank(value)) {
      String strFormat = "HH:mm";
      int intMatches = StringUtils.countMatches(value, ":");
      if (intMatches == 2) {
        strFormat = "HH:mm:ss";
      }
      SimpleDateFormat format = new SimpleDateFormat(strFormat);
      Date date = null;
      try {
        date = format.parse(value);
      } catch (Exception e) {
        e.printStackTrace();
      }
      time = new Time(date.getTime());
    }
    return time;
  }

}
原文地址:https://www.cnblogs.com/huiy/p/9482374.html