软件编程
位置:首页>> 软件编程>> java编程>> springmvc实现自定义类型转换器示例

springmvc实现自定义类型转换器示例

作者:_故乡的原风景  发布时间:2021-09-29 23:46:53 

标签: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>

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

来源:http://www.cnblogs.com/hy87/p/6322300.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com