@ConfigurationpublicclassAppConfig { @BeanpublicFormattingConversionServiceconversionService() {// Use the DefaultFormattingConversionService but do not register defaultsDefaultFormattingConversionService conversionService =newDefaultFormattingConversionService(false);// Ensure @NumberFormat is still supportedconversionService.addFormatterForFieldAnnotation(newNumberFormatAnnotationFormatterFactory());// Register JSR-310 date conversion with a specific global formatDateTimeFormatterRegistrar registrar =newDateTimeFormatterRegistrar();registrar.setDateFormatter(DateTimeFormatter.ofPattern("yyyyMMdd"));registrar.registerFormatters(conversionService);// Register date conversion with a specific global formatDateFormatterRegistrar registrar =newDateFormatterRegistrar();registrar.setFormatter(newDateFormatter("yyyyMMdd"));registrar.registerFormatters(conversionService);return conversionService; }}
如果您更喜欢基于 XML 的配置,可以使用 FormattingConversionServiceFactoryBean. 以下示例显示了如何执行此操作: