springmvc除了自带的部分类型转换之外,还可以自定义类型转换器,按照以下步骤:
1、写一个类实现Converter接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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
1
2
3
4
5
6
7
8
|
< 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
1
2
|
< mvc:annotation-driven conversion-service = "conversionService" >
</ mvc:annotation-driven >
|
这样在类型转化的过程中就会自动调用这个转换器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/hy87/p/6322300.html