首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将spring org.springframework.format.annotation.DateTimeFormat强制到自定义DateFormatter

如何将spring org.springframework.format.annotation.DateTimeFormat强制到自定义DateFormatter
EN

Stack Overflow用户
提问于 2019-03-06 17:29:49
回答 1查看 573关注 0票数 0

我有一个场景,我有不同类型的日期即将到来,在这种情况下,现有的春季转换失败了,因为vales以不同的格式出现。

有办法让Spring使用我的自定义DateFormatter吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-06 20:39:23

有办法让Spring使用我的自定义DateFormatter吗?

是的,但是由于您的用例是特定的,我认为最好使用自定义注释来显化所有内容。

这些interface可用于完成此任务:

这些类源代码可用作参考:

你可以这样做:

UnstableDateFormats注释

代码语言:javascript
复制
@Retention(RUNTIME)
public @interface UnstableDateFormats {
  String[] formatsToTry();
}

Formatter实现

代码语言:javascript
复制
public class UnstableDateFormatter implements Formatter<LocalDate> {
  private final List<String> formatsToTry;

  public UnstableDateFormatter(List<String> formatsToTry) {
    this.formatsToTry = formatsToTry;
  }

  @Override
  public LocalDate parse(String text, Locale locale) throws ParseException {
    for (String format : formatsToTry) {
      try {
        return LocalDate.parse(text, DateTimeFormatter.ofPattern(format));
      } catch (DateTimeParseException ignore) {
        // or log the exception
      }
    }
    throw new IllegalArgumentException("Unable to parse \"" + text
        + "\" as LocalDate using formats = " + String.join(", ", formatsToTry));
  }

  @Override
  public String print(LocalDate object, Locale locale) {
    // Implement this method thoroughly
    // If you're accepting dates in different formats which one should be used to print the value?
    return object.toString();
  }
}

AnnotationFormatterFactory实现

代码语言:javascript
复制
public class UnstableDateFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<UnstableDateFormats> {
  @Override
  public Set<Class<?>> getFieldTypes() {
    return Collections.singleton(LocalDate.class);
  }

  @Override
  public Printer<?> getPrinter(UnstableDateFormats annotation, Class<?> fieldType) {
    return new UnstableDateFormatter(Arrays.asList(annotation.formatsToTry()));
  }

  @Override
  public Parser<?> getParser(UnstableDateFormats annotation, Class<?> fieldType) {
    return new UnstableDateFormatter(Arrays.asList(annotation.formatsToTry()));
  }
}

不要忘记注册AnnotationFormatterFactory实现

如果您正在使用spring,您可以在web配置中这样做(请参阅类型转换):

代码语言:javascript
复制
public class MvcConfig implements WebMvcConfigurer {
  @Override
  public void addFormatters(FormatterRegistry registry) {
    registry.addFormatterForFieldAnnotation(new UnstableDateFormatAnnotationFormatterFactory());
  }
}

另请参阅:

你也可以考虑:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55028978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档