springboot 自定义 formatter 注解

我们在开发时会用到 @DateTimeFormat 这个注解。

对于从前台接收时间日期格式 很方便。

但如果前台传来的是 "是" “否” “有” "无" 这样的中文时,想要转成boolean 类型时,没有对应的注解,下面我们自己来实现这个注解。

本例基于

springboot 2.x

jdk1.8

首先,创建一个注解

复制代码
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
public @interface BooleanFormat {
    String[] trueTag() default {}; }
复制代码

其中 trueTag  用于接收参数

比如我们想将 “YES”,“OK” 这样的字符串转成 true ,那需要在参数中进行表示 。

然后,我们建一个formatter类,帮助我们来实现具体的转换规则。

复制代码
 1 public class BooleanFormatter implements Formatter<Boolean> {
 2  3 private String[] trueTag;  4  5  6  @Override  7 public Boolean parse(String s, Locale locale) throws ParseException {  8 if (trueTag != null && trueTag.length > 0) {  9 return Arrays.asList(trueTag).contains(s); 10 } else { 11 switch (s.toLowerCase()) { 12 case "true": 13 case "1": 14 case "是": 15 case "有": 16 return true; 17  } 18  } 19 return false; 20  } 21 22  @Override 23 public String print(Boolean aBoolean, Locale locale) { 24 return aBoolean ? "true" : "false"; 25  } 26 27 public String[] getTrueTag() { 28 return trueTag; 29  } 30 31 public void setTrueTag(String[] trueTag) { 32 this.trueTag = trueTag; 33  } 34 }
复制代码

第3行的属性用来接收注解上传过来的参数。

第7行的方法是用于将字符串转成BOOLEAN类型。

第23行的方法用于将BOOLEAN类型转成字符串。

完成上面的代码后,我们还需要将我们自定义的类型转类注册到spring中。

先定义一下factory类。

复制代码
 1 public class BooleanFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
 2 implements AnnotationFormatterFactory<BooleanFormat> {  3  4  5  @Override  6 public Set<Class<?>> getFieldTypes() {  7 return new HashSet<Class<?>>(){{  8 add(String.class);  9 add(Boolean.class); 10  }}; 11 12  } 13 14  @Override 15 public Printer<?> getPrinter(BooleanFormat booleanFormat, Class<?> aClass) { 16 BooleanFormatter booleanFormatter = new BooleanFormatter(); 17  booleanFormatter.setTrueTag(booleanFormat.trueTag()); 18 return booleanFormatter; 19  } 20 21  @Override 22 public Parser<?> getParser(BooleanFormat booleanFormat, Class<?> aClass) { 23 BooleanFormatter booleanFormatter = new BooleanFormatter(); 24  booleanFormatter.setTrueTag(booleanFormat.trueTag()); 25 return booleanFormatter; 26  } 27 }
复制代码

然后将这个类注册到spring中。

复制代码
 1 @Configuration
 2 public class WebConfigurer implements WebMvcConfigurer {  3  4  5  6  @Override  7 public void addFormatters(FormatterRegistry registry) {  8 registry.addFormatterForFieldAnnotation(new BooleanFormatAnnotationFormatterFactory());  9  } 10 11 12 }
复制代码

接下来,就可以使用这个注解了。

在你的pojo类中:

1 @Data
2 public class DemoDto { 3 @BooleanFormat(trueTag = {"YES","OK","是"}) 4 private boolean exists; 5 }

猜你喜欢

转载自www.cnblogs.com/jc1997/p/11037571.html