21 Eylül 2021 Salı

SpringConverters Converter Arayüzü

Giriş
Şu satırı dahil ederiz
import org.springframework.core.convert.converter.Converter;
Örnek
Şöyle yaparız
@Component
public class LocalDateConverter implements Converter<String, LocalDate> {

  static final List<String> SUPPORTED_FORMATS = Arrays.asList("dd-MM-yyyy", "yyyy-MM-dd");
  static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = SUPPORTED_FORMATS
    .stream()
    .map(DateTimeFormatter::ofPattern)
    .collect(Collectors.toList());

  @Override
  public LocalDate convert(String s) {
    for (DateTimeFormatter dateTimeFormatter : DATE_TIME_FORMATTERS) {
      try {
        return LocalDate.parse(s, dateTimeFormatter);
      } catch (DateTimeParseException ex) {
        // deliberate empty block so that all parsers run
      }
    }

    throw new DateTimeException(String.format("unable to parse (%s) supported formats are %s",
      s, String.join(", ", SUPPORTED_FORMATS)));
  }
}

Hiç yorum yok:

Yorum Gönder