Spring中字段格式化的使用详解

开发 架构
Spring提供的一个core.convert包是一个通用类型转换系统。它提供了统一的ConversionService API和强类型的Converter SPI,用于实现从一种类型到另一种类型的转换逻辑。

环境: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。

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。

  1. getFieldTypes()返回可以使用注释的字段类型。
  2. getPrinter()返回一个Printer来打印带注释的字段的值。
  3. 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的一个实现,适用于大多数环境。可以通过编程或声明的方式将该变体配置为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;
}
}
}
责任编辑:姜华 来源: 今日头条
相关推荐

2010-03-16 11:20:38

Python格式化

2009-08-03 16:24:05

C#格式化

2010-07-16 15:23:34

Perl格式化输出

2010-07-16 14:37:26

Perl格式化输出

2019-05-17 13:20:57

Black格式化工具Python

2023-04-11 10:37:40

bash命令printf

2010-07-15 11:29:25

Perl格式化输出

2020-09-02 07:19:41

printf 格式化输出Unix

2009-08-03 14:25:59

C#日期格式化

2009-06-05 15:27:23

Eclipse工具格式化模板应用

2010-08-03 10:46:41

Flex代码格式化

2009-07-02 10:14:15

格式化日期SQL Server

2020-11-03 10:21:33

MySQL

2010-07-29 11:12:30

Flex日期格式化

2018-11-02 10:45:35

windowsU盘格式化

2010-10-28 15:32:42

oracle日期格式化

2022-05-17 07:54:40

代码前端格式化

2022-05-09 14:04:27

Python字符串格式化输出

2010-06-28 10:45:44

Sql Server日

2010-01-21 13:41:05

VB.NET磁盘格式化
点赞
收藏

51CTO技术栈公众号