环境:Spring5.3.12.RELEASE。

Spring提供的一个core.convert包是一个通用类型转换系统。它提供了统一的ConversionService API和强类型的Converter SPI,用于实现从一种类型到另一种类型的转换逻辑。Spring容器使用这个系统绑定bean属性值。此外,Spring Expression Language (SpEL)和DataBinder都使用这个系统来绑定字段值。例如,当SpEL需要将Short强制转换为Long来完成表达式时。setValue(对象bean,对象值)尝试,核心。转换系统执行强制转换。
现在考虑典型客户端环境(例如web或桌面应用程序)的类型转换需求。在这种环境中,通常从String转换为支持客户端回发过程,并返回String以支持视图呈现过程。此外,你经常需要本地化String值。更一般的core.convert Converter SPI不能直接解决这些格式要求。为了直接解决这些问题,Spring 3引入了一个方便的Formatter SPI,它为客户端环境提供了PropertyEditor实现的一个简单而健壮的替代方案。
通常,当你需要实现通用类型转换逻辑时,你可以使用Converter SPI,例如,用于java.util.Date和Long之间的转换。当你在客户端环境(例如web应用程序)中工作并需要解析和打印本地化的字段值时,你可以使用Formatter SPI。ConversionService为这两个spi提供了统一的类型转换API。
实现字段格式化逻辑的Formatter SPI是简单且强类型的。下面的清单显示了Formatter接口定义:
package org.springframework.format;
public interface Formatterextends Printer , Parser { 
}
Formatter继承自Printer和Parser接口。
@FunctionalInterface
public interface Printer{ 
String print(T object, Locale locale);
}
@FunctionalInterface
public interface Parser{ 
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{ 
@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(类型转换接口)。
字段格式化可以通过字段类型或注释进行配置。要将注释绑定到Formatter,请实现AnnotationFormatterFactory。
public interface AnnotationFormatterFactory {
Set> getFieldTypes(); 
Printer> getPrinter(A annotation, Class> fieldType);
Parser> getParser(A annotation, Class> fieldType);
}
类及其方法说明:
参数化A为字段注解类型,你希望将该字段与格式化逻辑关联,例如org.springframework.format.annotation.DateTimeFormat。
自定义注解解析器。
public class StringToDateFormatter implements AnnotationFormatterFactory{ 
@Override
public Set> getFieldTypes() { 
return new HashSet>(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{ 
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);
  }
}
FormatterRegistry是用于注册格式化程序和转换器的SPI。FormattingConversionService是FormatterRegistry的一个实现,适用于大多数环境。可以通过编程或声明的方式将该变体配置为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);
}
@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中字段格式化的使用详解
                
                网站地址:http://www.csdahua.cn/qtweb/news3/329353.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网