-
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 생성
12345678910111213141516171819202122232425262728293031323334353637383940public 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 Scripterhttp://col EventConverter 생성
-> 아래와 같이 String to Int 메서드를 오버라이딩하는 StringToEventConverter 클래스
-> 아래와 같이 Event to String 메서드를 오버라이딩하는 EventToStringConverter 클래스 생성
123456789101112131415161718192021222324252627282930313233package com.example.demo;import org.springframework.stereotype.Component;public class EventConverter {public static class StringToEventConverter implements Converter<String, Event> {@Overridepublic Event convert(String source) {// TODO Auto-generated method stubreturn new Event(Integer.parseInt(source));}}public static class EventToStringConverter implements Converter<Event, String> {@Overridepublic String convert(Event source) {// TODO Auto-generated method stub}}}http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color ScripterConfiguration 생성
->Converter와 Formatter를 설정파일에 등록해야 사용가능하다.
1234567891011121314151617181920212223242526272829package com.example.demo;import java.util.Set;import org.springframework.context.annotation.Configuration;import org.springframework.context.support.ConversionServiceFactoryBean;import org.springframework.format.FormatterRegistry;@Configurationpublic class WebConfig implements WebMvcConfigurer{@Overridepublic void addFormatters(FormatterRegistry formatterRegistry) {// 1. ConverterformatterRegistry.addConverter(new EventConverter.StringToEventConverter());// 2. FormattersformatterRegistry.addFormatter(new EventFormatter());}}http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color ScripterFormatter 구현
Formatter는 제네릭으로 한개의 인자만을 받는다. Converter와 달리 Object와 String 간의 변환을 담당하기 때문이다.
12345678910111213141516171819202122232425package com.example.demo;import java.text.ParseException;import java.util.Locale;import org.springframework.format.Formatter;public class EventFormatter implements Formatter <Event> {@Overridepublic String print(Event object, Locale locale) {// TODO Auto-generated method stub}@Overridepublic Event parse(String text, Locale locale) throws ParseException {// TODO Auto-generated method stubreturn new Event(Integer.parseInt(text));}}http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color ScripterConversionService
- Converter와 Formatter 두 데이터 바인딩 인터페이스는 위에서 WebMvcConfigurer의 메서드를 통해 ConversionService에 등록된다.
1234567891011121314151617181920212223242526package com.example.demo;import org.springframework.stereotype.Component;@Componentpublic class AppRunner implements ApplicationRunner {@AutowiredConversionService conversionService;@Overridepublic void run(ApplicationArguments args) throws Exception {// TODO Auto-generated method stubSystem.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를 작성하고 테스트가 가능하다.
12345678910111213141516171819package com.example.demo;import org.springframework.stereotype.Controller;@RestControllerpublic class EventController {@GetMapping("/event/{event}")public String getEvent(@PathVariable Event event) {System.out.println(event);}}http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color ScripterEventController 테스트 'SPRING' 카테고리의 다른 글
Expression Language : SPEL 관련 정리 (0) 2020.04.30 ResourceLoader 관련 정리 (0) 2020.04.19 스프링 이벤트 프로그래밍 -ApplicationEventPublisher (0) 2020.04.19 스프링 MessageSource (0) 2020.04.15 스프링 Properties 관련 정리 (0) 2020.04.15