ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring Converter / Formatter를 이용한 데이터 바인딩
    SPRING 2020. 4. 26. 14:09

    Converter와 Formatter

     

    PropertyEditor는 스프링 초기(3.0이전)에 사용되었던 데이터 바인딩 인터페이스 였으나, 현재는 Converter와 Formatte라는 데이터 바인딩 인터페이스를 주로 사용하고 있다.

     

    Converter는 S타입을 T 타입으로 변환할 수 있는 일반적인 변환기이며 Thread-safe하다. 

    Formatter Object String간의 변환을 담당하며 역시 Thread-safe하다.

    또한  문자열을 Locale에 따라 다국화하는 기능을 제공한다. (Optional)

     

     

    Converter / Formatter 구현 및 테스트

     

    Event VO 생성

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
     
     
    public class Event {
        
        Integer id;
        String title;
     
        public Event() {
            
        }
        
        public Event(Integer id) {
            this.id =id;
        }
     
        public Event(Integer id, String title) {
            
            this.id = id;
            this.title = title;
        }
        
        public Integer getId() {
            return id;
        }
     
        public void setId(Integer id) {
            this.id = id;
        }
     
        public String getTitle() {
            return title;
        }
     
        public void setTitle(String title) {
            this.title = title;
        }
    }
     
     
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
    http://col

    EventConverter 생성 

    -> 아래와 같이 String to Int 메서드를 오버라이딩하는 StringToEventConverter 클래스

    -> 아래와 같이 Event to String 메서드를 오버라이딩하는 EventToStringConverter 클래스 생성

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
     
    import org.springframework.stereotype.Component;
     
    public class EventConverter {
     
        public static class StringToEventConverter implements Converter<String, Event> {
     
            @Override
            public Event convert(String source) {
                // TODO Auto-generated method stub
                return new Event(Integer.parseInt(source));
            }
            
            
        }
        
        public static class EventToStringConverter implements Converter<Event, String> {
     
            @Override
            public String convert(Event source) {
                // TODO Auto-generated method stub
                return source.getId().toString();
            }
            
        }
        
        
        
    }
     
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

     

    Configuration 생성

    ->Converter와 Formatter를 설정파일에 등록해야 사용가능하다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
     
     
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.support.ConversionServiceFactoryBean;
    import org.springframework.format.FormatterRegistry;
     
    @Configuration
    public class WebConfig implements WebMvcConfigurer{
     
        @Override
        public void addFormatters(FormatterRegistry formatterRegistry) {
            
            // 1. Converter
            formatterRegistry.addConverter(new EventConverter.StringToEventConverter());
            
            // 2. Formatters
            formatterRegistry.addFormatter(new EventFormatter());
            
        }
     
    }
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

    Formatter 구현

    Formatter는 제네릭으로 한개의 인자만을 받는다. Converter와 달리 Object와 String 간의 변환을 담당하기 때문이다.

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
     
     
    import org.springframework.format.Formatter;
     
    public class EventFormatter implements Formatter <Event> {
     
        @Override
        public String print(Event object, Locale locale) {
            // TODO Auto-generated method stub
            return object.getId().toString();
        }
     
        @Override
        public Event parse(String text, Locale locale) throws ParseException {
            // TODO Auto-generated method stub
            return new Event(Integer.parseInt(text));
        }
     
        
        
    }
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

     

    ConversionService

     

    - Converter Formatter 두 데이터 바인딩 인터페이스는 위에서 WebMvcConfigurer의 메서드를 통해 ConversionService에 등록된다.

     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
    import org.springframework.stereotype.Component;
     
    @Component
    public class AppRunner implements ApplicationRunner {
     
        @Autowired
        ConversionService conversionService;
     
        @Override
        public void run(ApplicationArguments args) throws Exception {
            // TODO Auto-generated method stub
            System.out.println(conversionService.getClass().toString());
     
     
        }
        
        
     
    }
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

    그러나 스프링 부트에서는 Formatter와 Converter를 Component로 등록하면 위와 같이 WebMvcConfigurer를 사용하지 않을 수 있다.

     

    ex : ) @Component

            public class EventFormatter implements Formatter <Event>

     

     

    아래와 같이 Controller를 작성하고 테스트가 가능하다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    import org.springframework.stereotype.Controller;
     
    @RestController
    public class EventController {
     
        @GetMapping("/event/{event}")
        public String getEvent(@PathVariable Event event) {
            System.out.println(event); 
            return event.getId().toString();
        }
        
    }
     
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

     

    EventController 테스트

     

Designed by Tistory.