Spring Converter 入门之字符串转化为枚举,springconverter
分享于 点击 37190 次 点评:9
Spring Converter 入门之字符串转化为枚举,springconverter
Converter是Spring3中引入的一项比较特殊的功能,其实就是一个转换器,可以把一种类型转换为另一种类型。尤其是在web项目中比较常见,可以对接口的入参做校验,把前端的入参的类型转换后为后端可以使用的类型。如常常用来做类型转换、字符串去空、日期格式化等。在Spring3之前进行类型转换都是使用PropertyEditor,使用PropertyEditor的setAsText()方法可以实现String转向特定的类型,但是它的最大的一个缺陷就是只支持String转为其他类型。 Spring中的三种类型转换接口分别为:- Converter接口:使用最简单,但是不太灵活;
- ConverterFactory接口:使用较复杂,稍微灵活一点;
- GenericConverter接口:使用最复杂,也最灵活;
- 首先了解一下Converter接口
package org.springframework.core.convert.converter; public interface Converter<S, T> { T convert(S var1); }即可以把S类型转化为T类型,并支持泛型。
- 首先建立一个简单的对象类Person
public class Person { private String name; private GenderEnum type; public Person() { } public Person(GenderEnum type, String name) { this.type = type; this.name = name; } public GenderEnum getType() { return type; } public void setType(GenderEnum type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person{" + "type=" + type + ", name='" + name + '\'' + '}'; } }
- 需要转化的枚举类
public enum GenderEnum { male("male"), female("female"); private final String value; GenderEnum(String v) { this.value = v; } public String toString() { return this.value; } public static GenderEnum get(int v) { String str = String.valueOf(v); return get(str); } public static GenderEnum get(String str) { for (GenderEnum e : values()) { if (e.toString().equals(str)) { return e; } } return null; } }
- Convert转换类
final class StringToGenderEnumConverter implements Converter<String, GenderEnum> { @Override public GenderEnum convert(String source) { String value = source.trim(); if ("".equals(value)) { return null; } return GenderEnum.get(Integer.parseInt(source)); } }
- spring-mvc.xml配置
<mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" <property name="converters" <set> <bean class="com.chenyufeng.springmvc.common.converter.StringToGenderEnumConverter"/> </set> </property> </bean>
- Controller
@Api(value = "converter", description = "自动转换", produces = MediaType.APPLICATION_JSON_VALUE) @Controller @RequestMapping("/converter") public class ConverterController { @Autowired private ConverterService converterService; @RequestMapping(value = "/savePerson", method = RequestMethod.GET) @ResponseBody public String savePerson( @ApiParam(value = "type") @RequestParam GenderEnum type, @ApiParam(value = "ID") @RequestParam String id) { Person person = new Person(type, id); return converterService.savePerson(person); } }以上案例上传至:https://github.com/chenyufeng1991/StartSpringMVC_Modules中。
用户点评