Formatter와 Converter

최기곤·2021년 1월 14일
0

스프링MVC

목록 보기
7/9

Formatter

  • Object와 String간의 변환을 담당하며 문자열을 Locale에 따라 다국화하는 기능을 제공한다.
    formmater객체
public class EventFormatter implements Formatter<Event> {
  @Override
  public Event parse(String text, Locale locale) throws ParseException {
      return new Event(Integer.parseInt(text));
  }

  @Override
  public String print(Event object, Locale locale) {
      return object.getId().toString();
  }
}

등록

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new EventFormatter());
    }
}

스프링의 경우에는 이처럼 Formatter를 등록할 수 있다.
스프링 부트의 경우에는 WebConversionService가 Formmater를 자동으로 등록해준다. 따라서 Formatter객체에 @Component만 붙여주면 된다!

Converter

  • S타입을 T타입으로 변환할 수 있는 일반적인 변환기이며 Thread-safe하다.
public class EventConverter  {
    public static class StringToEventConverter implements Converter<String, Event> {
        @Override
        public Event convert(String source){
            return new Event(Integer.parseInt(source));
        }
    }

    public static class EventToStringConverter implements Converter<Event, String>{
        @Override
        public String convert(Event source){
            return source.getId().toString();
        }
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new EventConverter.StringToEventConverter());
    }
}
  • Formatter와 같이 Converter또한 스프링과 스프링부트에서 등록 방식이 똑같다.
profile
놀면서 일하고 일하면서 놀고~ 해삐~

0개의 댓글