# 自定义类型转换

SpringMVC 中实现自定义的参数类型转换有两种途径:

  • 实现 Converter 接口

  • 实现 Formatter 接口

# 使用 Converter 接口

通过 Convert 接口来实现自定义转换及参数绑定,需要为 Spring 提供一个实现了 Converter 接口的类,并在 Spring MVC 中进行注册。

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

public class DateConverter implements Converter<String, Date> {
    ...
}
  • 配置文件版:spring-web.xml

    <mvc:annotation-driven conversion-service="conversionService"/>
    
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
      <property name="converters">
        <set>
          <bean class="com.demo1.converter.MyConverter"/>
        </set>
      </property>
    </bean>
    
  • 代码配置版:SpringWebConfig.java

    @Override
    public void addFormatters(FormatterRegistry registry) {
          registry.addConverter(new MyDateConverter());
      //  registry.addFormatter(new MyDateFormatter());
      }
    
  • Converter 接口的核心内容:

    @Override
    public Date convert(String str) {
    
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
      Date date = null;
      try {
        date = simpleDateFormat.parse(str);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    
      return date;
    }
    

# 使用 Formatter 接口(了解、自学)

Formatter 接口的使用于 Converter 接口类似。

public DateFormatter(String datePattern) {
  dateFormat = new SimpleDateFormat("MM-dd-yyyy");
}

@Override
public String print(Date object, Locale locale) {
  return dateFormat.format(object);
}

@Override
public Date parse(String text, Locale locale) throws ParseException {
  return dateFormat.parse(text);
}
  • 配置文件版:spring-web.xml

    <mvc:annotation-driven conversion-service="conversionService"/>
    
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
      <property name="formatters">
        <set>
          <bean class="com.demo.web.support.DateFormatter"/>
        </set>
      </property>
    </bean>
    
  • 代码配置版:SpringWebConfig.java

    见上。