我们在开发时会用到 @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<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 类型转成字符串.
完成上面的代码后, 我们还需要将我们自定义的类型转类注册到 spring 中.
先定义一下 factory 类.
- 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());
- }
- }
接下来, 就可以使用这个注解了.
在你的 pojo 类中:
- @Data
- public class DemoDto {
- @BooleanFormat(trueTag = {"YES","OK","是"})
- private boolean exists;
- }
来源: http://www.bubuko.com/infodetail-3094883.html