스프링 Formatter 적용

스프링 Formatter 적용

728x90

포맷터 생성

package hello.typeconverter.formatter; import lombok.extern.slf4j.Slf4j; import org.springframework.format.Formatter; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; @Slf4j public class MyNumberFormatter implements Formatter { @Override public Number parse(String text, Locale locale) throws ParseException { log.info("text={}, locale={}", text, locale); NumberFormat format = NumberFormat.getInstance(locale); return format.parse(text); } @Override public String print(Number object, Locale locale) { log.info("object={}, localse={}", object, locale); return NumberFormat.getInstance(locale).format(object); } }

포멧터 등록

WebMvcConfigurer 는 포멧터랑 컨버터 둘다 적용 가능

package hello.typeconverter; import hello.typeconverter.converter.IntegerToStringConverter; import hello.typeconverter.converter.IpPortToStringConverter; import hello.typeconverter.converter.StringToIntegerConverter; import hello.typeconverter.converter.StringToIpPortConverter; import hello.typeconverter.formatter.MyNumberFormatter; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { // 주석처리 우선순위 // registry.addConverter(new StringToIntegerConverter()); // registry.addConverter(new IntegerToStringConverter()); // registry.addConverter(new StringToIpPortConverter()); // registry.addConverter(new IpPortToStringConverter()); //추가 registry.addFormatter(new MyNumberFormatter()); } }

728x90

from http://arch1tect.tistory.com/187 by ccl(A) rewrite - 2021-10-04 00:27:10