我们在开发时会用到 @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类,帮助我们来实现具体的转换规则。
public class BooleanFormatter implements Formatter {
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类型转成字符串。
完成上面的代码后,我们还需要将我们自定义的类型转类注册到spring中。
先定义一下factory类。
public class BooleanFormatAnnotationFormatterFactory extends EmbeddedValueResolutionSupport
implements AnnotationFormatterFactory {
private static final Set<Class<?>> FIELD_TYPES;
static {
FIELD_TYPES = new HashSet<>(1);
FIELD_TYPES.add(String.class);
}
@Override
public Set<Class<?>> getFieldTypes() {
return FIELD_TYPES;
}
@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());
}
}
接下来,就可以使用这个注解了。
在你的pojo类中:
1 @Data
2 public class DemoDto {
3 @BooleanFormat(trueTag = {“YES”,“OK”,“是”})
4 private boolean exists;
5 }
原文:https://www.cnblogs.com/eclipse-/archive/2019/06/10/10998269.html