我有一个场景,我有不同类型的日期即将到来,在这种情况下,现有的春季转换失败了,因为vales以不同的格式出现。
有办法让Spring使用我的自定义DateFormatter吗?
发布于 2019-03-06 20:39:23
有办法让Spring使用我的自定义DateFormatter吗?
是的,但是由于您的用例是特定的,我认为最好使用自定义注释来显化所有内容。
这些interface可用于完成此任务:
这些类源代码可用作参考:
Jsr310DateTimeFormatAnnotationFormatterFactoryDateTimeFormatAnnotationFormatterFactoryNumberFormatAnnotationFormatterFactory你可以这样做:
UnstableDateFormats注释
@Retention(RUNTIME)
public @interface UnstableDateFormats {
String[] formatsToTry();
}Formatter实现
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实现
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配置中这样做(请参阅类型转换):
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addFormatterForFieldAnnotation(new UnstableDateFormatAnnotationFormatterFactory());
}
}另请参阅:
你也可以考虑:
https://stackoverflow.com/questions/55028978
复制相似问题