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 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM