亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring中字段格式化的使用小結

 更新時間:2022年06月26日 11:46:21   作者:Spring全家桶實戰(zhàn)案例  
Spring提供的一個core.convert包?是一個通用類型轉換系統(tǒng)。它提供了統(tǒng)一的?ConversionService??API和強類型的Converter SPI,用于實現從一種類型到另一種類型的轉換邏輯,這篇文章主要介紹了Spring中字段格式化的使用詳解,需要的朋友可以參考下

Spring提供的一個core.convert包 是一個通用類型轉換系統(tǒng)。它提供了統(tǒng)一的 ConversionService   API和強類型的Converter SPI,用于實現從一種類型到另一種類型的轉換邏輯。Spring容器使用這個系統(tǒng)綁定bean屬性值。此外,Spring Expression Language (SpEL)和DataBinder都使用這個系統(tǒng)來綁定字段值。例如,當SpEL需要將Short強制轉換為Long來完成表達式時。setValue(對象bean,對象值)嘗試,核心。轉換系統(tǒng)執(zhí)行強制轉換。

現在考慮典型客戶端環(huán)境(例如web或桌面應用程序)的類型轉換需求。在這種環(huán)境中,通常從String轉換為支持客戶端回發(fā)過程,并返回String以支持視圖呈現過程。此外,你經常需要本地化String值。更一般的core.convert Converter SPI不能直接解決這些格式要求。為了直接解決這些問題,Spring 3引入了一個方便的Formatter SPI,它為客戶端環(huán)境提供了PropertyEditor實現的一個簡單而健壯的替代方案。

通常,當你需要實現通用類型轉換邏輯時,你可以使用Converter SPI,例如,用于java.util.Date和Long之間的轉換。當你在客戶端環(huán)境(例如web應用程序)中工作并需要解析和打印本地化的字段值時,你可以使用Formatter SPI。ConversionService為這兩個spi提供了統(tǒng)一的類型轉換API。

1、Formatter SPI

實現字段格式化邏輯的Formatter SPI是簡單且強類型的。下面的清單顯示了Formatter接口定義:

package org.springframework.format;
public interface Formatter<T> extends Printer<T>, Parser<T> {
}

Formatter繼承自Printer和Parser接口。

@FunctionalInterface
public interface Printer<T> {
  String print(T object, Locale locale);
}
@FunctionalInterface
public interface Parser<T> {
  T parse(String text, Locale locale) throws ParseException;
}

默認情況下Spring容器提供了幾個Formatter實現。數字包提供了NumberStyleFormatter、CurrencyStyleFormatter和PercentStyleFormatter來格式化使用java.text.NumberFormat的number對象。datetime包提供了一個DateFormatter來用java.text.DateFormat格式化 java.util.Date對象。

自定義Formatter。

public class StringToNumberFormatter implements Formatter<Number> {
  @Override
  public String print(Number object, Locale locale) {
    return "結果是:" + object.toString();
  }
  @Override
  public Number parse(String text, Locale locale) throws ParseException {
    return NumberFormat.getInstance().parse(text);
  }
}

如何使用?我們可以通過FormattingConversionService 轉換服務進行添加自定義的格式化類。

FormattingConversionService fcs = new FormattingConversionService();
// 默認如果不添加自定義的格式化類,那么程序運行將會報錯
fcs.addFormatterForFieldType(Number.class, new StringToNumberFormatter());
Number number = fcs.convert("100.5", Number.class);
System.out.println(number);

查看源碼:

public class FormattingConversionService extends GenericConversionService implements FormatterRegistry, EmbeddedValueResolverAware {
  public void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter) {
    addConverter(new PrinterConverter(fieldType, formatter, this));
    addConverter(new ParserConverter(fieldType, formatter, this));
  }
  private static class PrinterConverter implements GenericConverter {}
  private static class ParserConverter implements GenericConverter {}
}
public class GenericConversionService implements ConfigurableConversionService {
  private final Converters converters = new Converters();
  public void addConverter(GenericConverter converter) {
    this.converters.add(converter);
  }
}

Formatter最后還是被適配成GenericConverter(類型轉換接口)。

2、基于注解的格式化

字段格式化可以通過字段類型或注釋進行配置。要將注釋綁定到Formatter,請實現AnnotationFormatterFactory。

public interface AnnotationFormatterFactory<A extends Annotation> {
  Set<Class<?>> getFieldTypes();
  Printer<?> getPrinter(A annotation, Class<?> fieldType);
  Parser<?> getParser(A annotation, Class<?> fieldType);
}

類及其方法說明:

參數化A為字段注解類型,你希望將該字段與格式化邏輯關聯,例如org.springframework.format.annotation.DateTimeFormat。

  • getFieldTypes()返回可以使用注釋的字段類型。
  • getPrinter()返回一個Printer來打印帶注釋的字段的值。
  • getParser()返回一個Parser來解析帶注釋字段的clientValue。

自定義注解解析器。

public class StringToDateFormatter implements AnnotationFormatterFactory<DateFormatter> {
  @Override
  public Set<Class<?>> getFieldTypes() {
    return new HashSet<Class<?>>(Arrays.asList(Date.class));
  }
  @Override
  public Printer<?> getPrinter(DateFormatter annotation, Class<?> fieldType) {
    return getFormatter(annotation, fieldType);
  }
  @Override
  public Parser<?> getParser(DateFormatter annotation, Class<?> fieldType) {
    return getFormatter(annotation, fieldType);
  }
  private StringFormatter getFormatter(DateFormatter annotation, Class<?> fieldType) {
    String pattern = annotation.value();
    return new StringFormatter(pattern);
  }
  class StringFormatter implements Formatter<Date> {
    private String pattern;
    public StringFormatter(String pattern) {
      this.pattern = pattern;
    }
    @Override
    public String print(Date date, Locale locale) {
      return DateTimeFormatter.ofPattern(pattern, locale).format(date.toInstant());
    }
    @Override
    public Date parse(String text, Locale locale) throws ParseException {
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, locale);
      return Date.from(LocalDate.parse(text, formatter).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }
  }
}

注冊及使用:

public class Main {
  @DateFormatter("yyyy年MM月dd日")
  private Date date;
  public static void main(String[] args) throws Exception {
    FormattingConversionService fcs = new FormattingConversionService();
    fcs.addFormatterForFieldAnnotation(new StringToDateFormatter());
    Main main = new Main();
    Field field = main.getClass().getDeclaredField("date");
    TypeDescriptor targetType = new TypeDescriptor(field);
    Object result = fcs.convert("2022年01月21日", targetType);
    System.out.println(result);
    field.setAccessible(true);
    field.set(main, result);
    System.out.println(main.date);
  }
}

3、FormatterRegistry

FormatterRegistry是用于注冊格式化程序和轉換器的SPI。FormattingConversionService是FormatterRegistry的一個實現,適用于大多數環(huán)境??梢酝ㄟ^編程或聲明的方式將該變體配置為Spring bean,例如使用FormattingConversionServiceFactoryBean。因為這個實現還實現了ConversionService,所以您可以直接配置它,以便與Spring的DataBinder和Spring表達式語言(SpEL)一起使用。

public interface FormatterRegistry extends ConverterRegistry {
  void addPrinter(Printer<?> printer);
  void addParser(Parser<?> parser);
  void addFormatter(Formatter<?> formatter);
  void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);
  void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);
  void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends Annotation> annotationFormatterFactory);
}

4、SpringMVC中配置類型轉換

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
  @Override
  public void addFormatters(FormatterRegistry registry) {
    // ...
  }
}

SpringBoot中有如下的默認類型轉換器。

public class WebMvcAutoConfiguration {
  public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration implements ResourceLoaderAware {
    @Bean
    @Override
    public FormattingConversionService mvcConversionService() {
      Format format = this.mvcProperties.getFormat();
      WebConversionService conversionService = new WebConversionService(new DateTimeFormatters().dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
      addFormatters(conversionService);
      return conversionService;
    }    
  }
}

到此這篇關于Spring中字段格式化的使用詳解的文章就介紹到這了,更多相關Spring字段格式化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論