当前位置:主页 > 软件编程 > JAVA代码 >

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

时间:2021-07-09 08:28:04 | 栏目:JAVA代码 | 点击:

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>

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

您可能感兴趣的文章:

相关文章