下面一个事例,是将传入的一个身份证号,转换成一个对象(提取身份证号的地址、出身日期、性别等)
实体类 Person 有三个字段如下:
String province; //地址 Date birthday; //出生日期 String sexual; //性别 Getter... Setter...
验证器实现 PersonFormatter:
实现 Formatter 接口,
public class PersonFormatter implements Formatter<Person> {
@Override
public Person parse(String text, Locale locale) throws ParseException {
//text参数是传进来的字符串,需要对字符串(身份证号)进行解析,并且保存到Person对象返回
return new Person();
} @Override
public String print(Person object, Locale locale) {
return null;
}}
自定义 PersonFormatterAnnotation 类,实现 AnnotationFormatterFactory 接口:
public class PersonFormatterAnnotation implements AnnotationFormatterFactory<PersonFormId> {
@Override
public Set<Class<?>> getFieldTypes() {
Set<Class<?>> types = new HashSet<>();
types.add(Person.class);
return types;
} @Override
public Printer<?> getPrinter(PersonFormId annotation, Class<?> fieldType) {
return null;
} @Override
public Parser<?> getParser(PersonFormId annotation, Class<?> fieldType) {
return getFormatter(annotation);
} private Formatter getFormatter(PersonFormId annotation) {
return new PersonFormatter();
}
}
spring xml文件代码:
<!-- 配置类型装换器 -->
<bean name="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="com.nf.lc.formatter.PersonFormatterAnnotation"></bean>
</set>
</property>
</bean>
spring中注册:
<!-- 启用MVC的常用注解 -->
<mvc:annotation-driven conversion-service="conversionService" />