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>
这样在类型转化的过程中就会自动调用这个转换器
时间: 2024-10-19 01:36:05