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类,帮助我们来实现具体的转换规则。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值