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> {
@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. Introduce ConversionServiceFactoryBean and inject the self-written classes into 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, in < mvc:annotation-driven > Tag the attributes ES16en-ES17en
<mvc:annotation-driven conversion-service="conversionService">
</mvc:annotation-driven>
This converter is called automatically during type conversion