데이터 바인딩 추상화 : Converter와 Formatter

| Converter

  • S타입을 T타입으로 변환할 수 있는 매우 일반적인 변환기
  • 상태정볻없음 == Stateless == 쓰레드세이프
  • ConverterRegistry에 등록해서 사용
package org.kyhslam;


import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

public class EventConverter {

    @Component
    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();
        }
    }
}

bean으로 만들지 않으려면 @Component를 제거하고 아래 코드 추가한다.

* WebConfiguration

  • WebMVC를 설정하는 파일이다.
  • addFormatters()를 오버라이드하고 addConverter로 등록한다.

 

| Formatter

  • Converter는 A를 B로 변환하고 싶다면 제네릭을 <A,B>로 작성해야 동작한다
  • Formatter는 양방향으로 작용할 수 잇는 두개의 메소드를 제공하여 조금 더 유연하다
package org.kyhslam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.Formatter;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Locale;

@Component
public class EventFormatter implements Formatter<Event> {

    @Override
    public Event parse(String s, Locale locale) throws ParseException {
        return new Event(Integer.parseInt(s));
    }

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

 

package org.kyhslam;

import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new EventFormatter());
    }
}
  • 여기서 이상한 점이 하나 있는데, converter를 등록할 때도 addFormatters를 상속받아 구현했다.
  • 잘 작동하는 이유는 Converter의 등록을 관리하는 ConverterRegistry 가 FormatterRegistry를 상속해서 만들었기 때문이다.
  • FormatterRegistry는 DefaultFormattingConversionService를 구현해서 만들었다.
  • DefaultFormattingConversionService 도 당연히 데이터 바인딩을 수행할 수 있다.
  • Spring boot에서는 ConversionService  @Autowired 로 주입받은 후 convert 메소드를 사용하면 된다.
  • conversionService.getClass() 를 콘솔에 찍어보면 application에 등록된 모든 converter, formatter 등을 확인해볼 수 있다.

'📚 Spring > Spring 개념' 카테고리의 다른 글

Spring AOP : 프록시 기반 AOP  (0) 2020.11.20
SpEL(스프링 Expression Language)  (0) 2020.10.05
데이터 바인딩 추상화 : PropertyEditor  (0) 2020.09.14
Resource 추상화  (0) 2020.09.14
IoC Container - ResourceLoader  (0) 2020.09.11

댓글

Designed by JB FACTORY