type converter : DefaultFormatterConversionService

This commit is contained in:
haerong22
2021-07-27 18:32:04 +09:00
parent 40f9c52c95
commit 4a10adc89e
2 changed files with 39 additions and 2 deletions

View File

@@ -4,6 +4,7 @@ import hello.typeconverter.converter.IntegerToStringConverter;
import hello.typeconverter.converter.IpPortToStringConverter; import hello.typeconverter.converter.IpPortToStringConverter;
import hello.typeconverter.converter.StringToIntegerConverter; import hello.typeconverter.converter.StringToIntegerConverter;
import hello.typeconverter.converter.StringToIpPortConverter; import hello.typeconverter.converter.StringToIpPortConverter;
import hello.typeconverter.fomatter.MyNumberFormatter;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry; import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -13,9 +14,11 @@ public class WebConfig implements WebMvcConfigurer {
@Override @Override
public void addFormatters(FormatterRegistry registry) { public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToIntegerConverter()); // registry.addConverter(new StringToIntegerConverter());
registry.addConverter(new IntegerToStringConverter()); // registry.addConverter(new IntegerToStringConverter());
registry.addConverter(new StringToIpPortConverter()); registry.addConverter(new StringToIpPortConverter());
registry.addConverter(new IpPortToStringConverter()); registry.addConverter(new IpPortToStringConverter());
registry.addFormatter(new MyNumberFormatter());
} }
} }

View File

@@ -0,0 +1,34 @@
package hello.typeconverter.fomatter;
import hello.typeconverter.converter.IpPortToStringConverter;
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;
import static org.assertj.core.api.Assertions.*;
public class FormattingConversionServiceTest {
@Test
void formattingConversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
// 컨버터 등록
conversionService.addConverter(new StringToIpPortConverter());
conversionService.addConverter(new IpPortToStringConverter());
// 포맷터 등록
conversionService.addFormatter(new MyNumberFormatter());
// 컨버터 사용
IpPort ipPort = conversionService.convert("127.0.0.1:8080", IpPort.class);
assertThat(ipPort).isEqualTo(new IpPort("127.0.0.1", 8080));
// 포맷터 사용
assertThat(conversionService.convert(1000, String.class)).isEqualTo("1,000");
assertThat(conversionService.convert("1,000", Long.class)).isEqualTo(1000L);
}
}