首页 > 代码库 > springmvc 自定义类型转换器
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>
这样在类型转化的过程中就会自动调用这个转换器
springmvc 自定义类型转换器
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。