美文网首页
SpringMVC自定义类型转换器

SpringMVC自定义类型转换器

作者: 夏睡醒了秋 | 来源:发表于2019-06-13 15:07 被阅读0次
1. 编写类并实现Converter接口(以字符串转日期为例)
package cn.test.utils;

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

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

/**
 * 字符串转日期
 */
public class StirngToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String s) {
        if(s == null){
            throw new RuntimeException("自定义类型转换器:字符串转换日期异常:参数:"+s);
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        try {
            return sf.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("自定义类型转换器:字符串转换日期异常:参数:"+s);
        }
    }
}

2. 配置自定义类型转换器(SpirngMVC)并使配置生效
<!--配置自定义类型转换器-->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.test.utils.StirngToDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--开启springmvc框架注解的支持,生效类型转换器-->
    <mvc:annotation-driven conversion-service="conversionService"/>
springmvc.xml

相关文章

网友评论

      本文标题:SpringMVC自定义类型转换器

      本文链接:https://www.haomeiwen.com/subject/bkhsfctx.html