springmvc 自定义类型转换器

springmvc除了自带的部分类型转换之外,还可以自定义类型转换器,按照以下步骤:

1、写一个类实现Converter接口

package com.hy.springmvc.entities;

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

import com.google.gson.Gson;

public class DepartmentConvertor implements Converter<String, Department> {

    @Override
    public Department convert(String source) {
        System.out.println("com.hy.springmvc.entities.DepartmentConvertor: "
                + source);
        Department department = new Gson().fromJson(source, Department.class);
        return department;
    }

}

2、引入ConversionServiceFactoryBean,将自己写的类注入到bean

<bean id="conversionService"
        class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.hy.springmvc.entities.DepartmentConvertor"></bean>
            </list>
        </property>
    </bean>

3、在<mvc:annotation-driven>里面标注属性conversion-service

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 

这样在类型转化的过程中就会自动调用这个转换器

 

posted on 2017-01-20 11:24  _故乡的原风景  阅读(237)  评论(0编辑  收藏  举报