카테고리 없음
formttingConvertionService
dev_0hoon
2023. 12. 20. 21:58
컨버전 서비스에는 컨버터만 등록 할 수 있다. 포메터는 등록할 수 없다.
하지만 포메터는 객체 -> 문자, 문자 -> 객체로 변환하는 특별한 컨버터 일 뿐이다.
그래서 포메팅컨버젼서비스에 등록해서 사용 할 수 있다.
package hello.typeconverter.formatter;
import hello.typeconverter.converter.IpPortToStringConverter;
import hello.typeconverter.converter.StringToIntegerConverter;
import hello.typeconverter.converter.StringToIpPortConverter;
import hello.typeconverter.type.IpPort;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.format.support.DefaultFormattingConversionService;
public class FormattingConversionServiceTest {
@Test
void formattingConversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
//컨버터 등록 (컨버터도 등록해서 사용 할 수 있다.)DefaultFormattingConversionService는 결국 컨버젼서비스도 상속받고 있기 떄문
conversionService.addConverter(new StringToIpPortConverter());
conversionService.addConverter(new IpPortToStringConverter());
//포메터 등록
conversionService.addFormatter(new MyNumberFormatter());
//컨버터 사용
IpPort ipPort = conversionService.convert("127.0.0.1:8080", IpPort.class);
Assertions.assertThat(ipPort).isEqualTo(new IpPort("127.0.0.1", 8080));
//포멧터 사용
Assertions.assertThat(conversionService.convert(1000,String.class)).isEqualTo("1,000");
Assertions.assertThat(conversionService.convert("1,000",Long.class)).isEqualTo(1000L);
}
}
test로 만들어 봤다.
DefaultFormattingConversionService 상속 관계
FormattingConversionService 는 ConversionService 관련 기능을 상속받기 때문에 결과적으로 컨버터도 포맷터도 모두 등록할 수 있다. 그리고 사용할 때는 ConversionService 가 제공하는 convert 를 사용하면 된다.
추가로 스프링 부트는 DefaultFormattingConversionService 를 상속 받은 WebConversionService 를 내부에서 사용한다.