springmvc implements a custom type converter example

  • 2020-06-07 04:33:18
  • OfStack

In addition to the partial type converters that come with springmvc, you can customize type converters by following these steps:

1. Write a class to implement the Converter interface

package com.hy.springmvc.entities;

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

import com.google.gson.Gson;

public class DepartmentConvertor implements Converter<String, Department> {

 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. Introduce ConversionServiceFactoryBean and inject the self-written classes into bean

<bean id="conversionService"
  <property name="converters">
    <bean class="com.hy.springmvc.entities.DepartmentConvertor"></bean>

3, in < mvc:annotation-driven > Tag the attributes ES16en-ES17en

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

This converter is called automatically during type conversion

Related articles: