数据绑定2-自定义注解实现Formatter
我们在开发时会用到 @DateTimeFormat 这个注解。
对于从前台接收时间日期格式 很方便。
但如果前台传来的是 "是" “否” “有” "无" 这样的中文时,想要转成boolean 类型时,没有对应的注解,下面我们自己来实现这个注解。
本例基于
springboot 2.x
jdk1.8
1. 创建自定义注解
BooleanFormat
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface BooleanFormat {
String[] trueTag() default {};
}
其中 trueTag 用于接收参数
比如我们想将 “YES”,“OK” 这样的字符串转成 true ,那需要在参数中进行表示 。
2. 创建Formatter
帮助我们来实现具体的转换规则
public class BooleanFormatter implements Formatter<Boolean> {
private String[] trueTag;
@Override
public Boolean parse(String s, Locale locale) throws ParseException {
if (trueTag != null && trueTag.length > 0) {
return Arrays.asList(trueTag).contains(s);
} else {
switch (s.toLowerCase()) {
case "true":
case "1":
case "是":
case "有":
return true;
}
}
return false;
}
@Override
public String print(Boolean aBoolean, Locale locale) {
return aBoolean ? "true" : "false";
}
public String[] getTrueTag() {
return trueTag;
}
public void setTrueTag(String[] trueTag) {
this.trueTag = trueTag;
}
}
第3行的属性用来接收注解上传过来的参数。
第7行的方法是用于将字符串转成BOOLEAN类型。
第23行的方法用于将BOOLEAN类型转成字符串。
3. 自定义的类型转类注册到spring
先定义factor
public class BooleanFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory<BooleanFormat> {
@Override
public Set<Class<?>> getFieldTypes() {
return new HashSet<Class<?>>(){{
add(String.class);
add(Boolean.class);
}};
}
@Override
public Printer<?> getPrinter(BooleanFormat booleanFormat, Class<?> aClass) {
BooleanFormatter booleanFormatter = new BooleanFormatter();
booleanFormatter.setTrueTag(booleanFormat.trueTag());
return booleanFormatter;
}
@Override
public Parser<?> getParser(BooleanFormat booleanFormat, Class<?> aClass) {
BooleanFormatter booleanFormatter = new BooleanFormatter();
booleanFormatter.setTrueTag(booleanFormat.trueTag());
return booleanFormatter;
}
}
然后将这个类注册到spring中
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new BooleanFormatAnnotationFormatterFactory());
}
}
4.使用这个注解
@Data
public class DemoDto {
@BooleanFormat(trueTag = {"YES","OK","是"})
private boolean exists;
}