1. Converter
1-1) Converter
Converter는 A 타입을 B 타입으로 변환할 수 있는 좀 더 일반적인 데이터 바인딩이 가능한 변환기임.
PropertyEditor와 다르게 상태 정보를 가지고 있지 않기 때문에 @Component 빈으로 등록해도 됨.
→ @Component로 빈으로 등록할 수 있으며 @AutoWired 주입도 받을 수 있음.
1-2) Converter Code
1-2)-1. class EventConverter
→ Converter라는 인터페이스를 구현하면 되는데 Generic Type으로 두 가지를 받음.
→ Converter<Source, Target> 형태를 띠며, Source를 Target으로 변환하겠다는 의미임.
→ 이렇게 작성된 두 클래스가 PropertyEditor와 같은 역할을 하며 얼마든지 빈으로 등록해서
→ 사용할 수 있음. 왜냐하면 상태 정보를 저장하고 있지 않기 때문임.
1-2)-2. class WebConfig
ConverterRegistry를 등록해서 EventConverter 사용하기
→ ConverterRegistry라는 인터페이스를 직접 등록해서 쓸 일은 없음.
→ SpringBoot 없이 Spring MVC를 사용한다면 WebConfig와 같은 Web용
→ Configuration 클래스를 만들고 WebMvcConfigurer를 구현함.
→ addFormatters를 Override하면 registry에 addConverter할 수 있는 메서드가 있음.
→ 여기에 Converter를 동록해주면 됨.
→ Spring MVC 설정에 넣어준 Converter가 모든 Controller에서 동작을 하게 됨.
1-2)-3. EventControllerTest의 Console
2. Formatter
2-1) Formatter
Formatter는 Converter보다 조금 더 Web쪽에 특화된 인터페이스임.
Formatter의 경우 처리할 타입을 하나 주고 두 개의 메서드를 구현함.
하나는 문자를 객체로, 다른 하나는 객체를 문자로 변환하는 메서드임.
→ @Component로 빈으로 등록할 수 있으며 @AutoWired 주입도 받을 수 있음.
2-2) Formatter Code
제너릭으로 하나의 인자만 받는 이유는 Object와 String 간의 변환에 사용되기 때문에
다른 하나의 인자가 String으로 고정되어있기 때문임.
한 가지 특징으로 Locale 정보를 기반으로 바꿀 수 있는 것인데,
이는 MessageSource를 공부할 때 나온 다국화와 관련된 기능임.
2-2)-1. class EventFormatter
2-2)-2. class WebConfig
ConverterRegistry를 등록해서 EventFormatter 사용하기
2-2)-3. EventControllerTest
3. ConversionService
3-1) ConversionService
앞서 PropertyEditor를 사용할 때 데이터 바인더를 통해 이용했다면
Converter와 Formatter를 사용할 때 ConversionService를 이용해야 함.
Converter와 Formatter 모두 ConversionService에 등록되어 변화하는 작업이 이뤄진 거임.
3-2)ConversionService가 사용되는 경우
3-3) DefaultFormattionConversionService
3-3)-1. DefaultFormattionConversionService 개념
스프링이 제공하는 ConversionService 구현체 중에 하나임. 이 클래스가 자주 사용됨.
이 클래스는 FormatterRegistry와 ConversionService 두 가지 인터페이스를
모두 구현했기 때문에 두 가지 기능의 역할을 함.
그 외에도 기본적인 Converter와 Formatter 등록을 해줌.
3-3)-2. Image
→ FormatterRegistry가 ConverterRegistry를 상속받고 있음.
→ Converter는 ConverterRegistry가 필요하며
→ Formatter는 FormatterRegistry가 필요한데, FormatterRegistry에서
→ Converter를 쓸 수 있었던 이유가 바로 이 때문임.
3-3)-3. class AppRunner
→ DefaultFormattionConversionService가 ConversionService의 역할도 한다고 함.
→ 이를 확인해보기 위해 AppRunner를 만들어서 실행해보자.
Console
→ 생각과 달리 DefaultFormattionConversionService가 아닌
→ WebConversionService가 출력되었다. 왜 그런것일까?
⇒ WebConversionService는 스프링 부트가 제공해주는 서비스이다.
⇒ 이 클래스는 DefaultFormattionConversionService를 상속해서 만든 것으로
=> 조금 더 많은 기능을 가지고 있다.
4. WebConversionService(SpringBoot)
SpringBoot를 사용할 경우 WebConversionService가 Formatter와 Converter를 자동으로 등록해줌.
즉, WebConfig와 같은 클래스 파일을 만들어서 스프링 웹 MVC 설정을 할 필요가 없다는 뜻임.
Converter나 Formatter가 빈으로 등록되어 있다면
스프링 부트가 자동으로 ConversionService를 등록해줌.
4-1) class EventConverter
4-2) class EventFormatter
4-3) EventControllerTest