카테고리 없음

spring mvc Conversion

머룽 2023. 4. 20. 09:53
이번 시간에 이전 시간에 살펴봤던 java config와 xml 설정중에 Conversion and Formatting 에 대해 알아보자. Conversion과 Formatting은 설정은 비슷하니까 Conversion만 알아보자.
@Override
public void addFormatters(FormatterRegistry registry){
}
위와 함수가 converter와 Formatter를 등록할 수 있는 함수이다. 그럼 사용하는 방법을 한번 살펴보자. 사용하는 형태는 여러가지가 있겠지만 여기서는 간단하게 enum을 컨버팅하는 것을 살펴보겠다.
public enum OrderType {
  CALL(1),
  ONLINE(2),
  OFFLINE(3);

  int i;
  OrderType(int i) {
    this.i = i;
  }

  public int getValue(){
    return i;
  }
  public static OrderType value(int value){
    switch (value){
      case 1 :
        return CALL;
      case 2:
        return ONLINE;
      case 3:
        return OFFLINE;
      default:
        return CALL;
    }
  }
}
우리는 이런 enum의 형태가 있다고 가정하자. 그럼 enum 타입을 request로 받을 때는 orderType을 String으로 받아야 된다. 예를 들어 이런식이다. orderType=CALL 하지만 필자는 저기 정의된 숫자로 받고 싶다고 가정하자. 그럼 어떻게 하면 될까? 그럴때 사용할 수 있는 것이 converter이다.
public class MyConverter implements Converter<String, OrderType> {

  public OrderType convert(String value) {
    return OrderType.value(Integer.parseInt(value));
  }
}
우리는 Spring에서 제공해주는 Converter 인터페이스를 사용하면 된다. 그럼 아주 간단하게 request에서 숫자로 받을 수가 있다. Converter의 첫번째 제네릭은 source type이고 두번째는 target type이다. 우리가 만든 Converter를 아까전에 말했던 addFormatters함수에서 등록시켜주자.
@Override
public void addFormatters(FormatterRegistry registry){
  registry.addConverter(new MyConverter());
}
그리고 나서 테스트를 하기 위해 Controller를 만든 후에 아래와 같이 작성하자.
@RequestMapping(value = "/test")
public void converterTest(@RequestParam OrderType orderType) {
  System.out.println(orderType);
}
그리고 실제로 request를 날려보면 orderType=CALL이 아닌 orderType=1로 request를 전달하면 매칭되어 출력된다. 아마도 Formatting도 비슷하게 작성하고 등록하면 될 듯 싶다. FormatterRegistry에는 addFormatter이라는 함수도 존재하고 있다.
FormatterRegistry.addFormatter(Formatter<?> formatter);
이상으로 Conversion and Formatting을 간단하게 알아봤다.