環境:Springboot2.6.12
通常,當需要實現通用類型轉換邏輯時,可以使用轉換器SPI?例如,用于在java.util.Date和Long之間轉換。當你在客戶端環境(如web應用程序)中工作并且需要解析和打印本地化字段值時,可以使用格式化程序SPI。ConversionService為兩個SPI提供統一的類型轉換API。
在Springboot環境下如何自定義數據類型的轉換?
Formatter SPI 實現字段格式化邏輯非常簡單,而且是強類型的。以下列表顯示格式化程序接口定義:
package org.springframework.format;public interface Formatter<T> extends Printer<T>, Parser<T> {}
Formatter 從Printer和Parser構建塊接口擴展而來。以下列表顯示了這兩個接口的定義:
public interface Printer<T> { String print(T fieldValue, Locale locale);}import java.text.ParseException;public interface Parser<T> { T parse(String clientValue, Locale locale) throws ParseException;}
要創建自己的Formatter格式化程序,只需要實現上面的Formatter接口。將泛型T替換為需要格式化的對象類型?—?例如,java.util.Date。實現print()操作以打印T的實例以在客戶端區域中顯示。實現parse()操作,從客戶端語言環境返回的格式化表示中解析T的實例。如果解析嘗試失敗,格式化程序應該拋出ParseException或IllegalArgumentException。注意確保格式化程序實現是線程安全的。
根據用戶輸入的信息,每個字段信息通過逗號分割,通過Formatter程序將其轉換為Users對象。如輸入:張三,30;將信息解析為Users對象姓名為張三,年齡為30。
public class Users { private String name ; private Integer age ;}
格式化程序:
public class UsersFormatter implements Formatter<Users> { @Override public String print(Users object, Locale locale) { if (Objects.isNull(object)) { return "" ; } return "【name = " + object.getName() + ", age = " + object.getAge() + "】" ; } @Override public Users parse(String text, Locale locale) throws ParseException { if (text == null || text.trim().length() == 0) { return null ; } Users user = new Users() ; // 下面做簡單處理,不做校驗 String[] values = text.split(",") ; user.setName(values[0]) ; user.setAge(Integer.parseInt(values[1])); return user ; }}
格式化程序定義完后,需要注冊到系統中讓系統能夠知道如何進行轉換。
@Configurationpublic class WebConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new UsersFormatter()) ; } }
測試接口:
@GetMapping("/save")public Object save(Users users) { return users ;}
輸出:
圖片
可以按字段類型或注解配置字段格式。要將注解綁定到格式化程序,需要實現
AnnotationFormatterFactory。以下顯示了AnnotationFormatterFactory接口的定義:
package org.springframework.format;public interface AnnotationFormatterFactory<A extends Annotation> { Set<Class<?>> getFieldTypes(); Printer<?> getPrinter(A annotation, Class<?> fieldType); Parser<?> getParser(A annotation, Class<?> fieldType);}
要創建實現,請執行以下操作:
參數化要與格式邏輯關聯的字段annotationType?—?例如org.springframework.format.annoation.DateTimeFormat。
自定義注解類,用來需要格式化的字段。
@Documented@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})public @interface AgeFormat {}
自定義注解格式化程序。
public final class AgeFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<AgeFormat> { public Set<Class<?>> getFieldTypes() { Set<Class<?>> types = new HashSet<Class<?>>() ; types.add(Integer.class) ; return types; } @Override public Printer<Integer> getPrinter(AgeFormat annotation, Class<?> fieldType) { return new AgeFormatter() ; } @Override public Parser<Integer> getParser(AgeFormat annotation, Class<?> fieldType) { return new AgeFormatter() ; } private class AgeFormatter implements Formatter<Integer> { @Override public String print(Integer object, Locale locale) { if (object == null) { return "" ; } return object.toString() ; } @Override public Integer parse(String text, Locale locale) throws ParseException { if (text == null || text.trim().length() == 0) { return -1 ; } return Integer.parseInt(text.substring(1)) ; } }}
注冊格式化程序。
@Configurationpublic class WebConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addFormatterForFieldAnnotation(new AgeFormatAnnotationFormatterFactory()) ; }}
Users.age字段添加注解。
public class Users { private String name ; @AgeFormat private Integer age ;}
測試接口。
@GetMapping("/save2")public Object save2(Users users) { return users ;}
注意這里的年齡前面加了一個‘s’字符。
格式化程序:
public final class UsersFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<UsersFormat> { public Set<Class<?>> getFieldTypes() { Set<Class<?>> types = new HashSet<Class<?>>() ; types.add(Users.class) ; return types; } @Override public Printer<?> getPrinter(UsersFormat annotation, Class<?> fieldType) { return new UsersFormatter(); } @Override public Parser<?> getParser(UsersFormat annotation, Class<?> fieldType) { return new UsersFormatter() ; }}
接口:
@GetMapping("/save3")public Object save3(@UsersFormat Users users) { return users ;}
完畢!!!
本文鏈接:http://www.tebozhan.com/showinfo-26-10556-0.htmlSpring強大的數據格式化處理功能,你必須得知道
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 如何使用Python構建OTP驗證系統?