che01 님의 블로그
Spring Formatter란 ? 본문
1. Formatter는 뭐하는 역할을 하나요?
Spring에서 Formatter는 문자(String) 와 객체(Object) 사이의 변환을 도와주는 도구입니다.
- 문자열을 → 객체로 변환하거나
- 객체를 → 문자열로 출력할 때
특히, 특정한 포맷(형식) 으로 값을 변환할 때 유용합니다. 예를 들어, 10000이라는 숫자를 10,000처럼 쉼표가 있는 형식으로 바꾸고 싶을 때 사용됩니다.
쉽게 말하면:
- Converter가 기본적인 타입 변환기라면,
- Formatter는 사람이 보기 좋은 형식으로 바꿔주는 변환기라고 생각하면 됩니다!
2. Formatter는 어떤 구조로 되어 있나요?
Spring에서 제공하는 Formatter는 두 가지 기능을 갖는 인터페이스입니다:
기능 설명
| parse() | 문자열을 객체로 변환 (예: "10,000" → 10000) |
| print() | 객체를 문자열로 변환 (예: 10000 → "10,000") |
public interface Formatter<T> {
T parse(String text, Locale locale); // 문자열 → 객체
String print(T object, Locale locale); // 객체 → 문자열
}
- Locale: 지역/언어 정보입니다. 예: 한국어 ko_KR, 영어 en_US
3. 직접 만든 Formatter 예시
가격을 쉼표 있는 형식으로 출력하는 Formatter
@Slf4j
public class PriceFormatter implements Formatter<Number> {
@Override
public Number parse(String text, Locale locale) throws ParseException {
log.info("text = {}, locale = {}", text, locale);
return NumberFormat.getInstance(locale).parse(text); // "10,000" → 10000
}
@Override
public String print(Number object, Locale locale) {
log.info("object = {}, locale = {}", object, locale);
return NumberFormat.getInstance(locale).format(object); // 10000 → "10,000"
}
}
4. 테스트 예시
@Test
void parse() throws ParseException {
PriceFormatter formatter = new PriceFormatter();
Number result = formatter.parse("1,000", Locale.KOREA);
assertThat(result).isEqualTo(1000L);
}
@Test
void print() {
PriceFormatter formatter = new PriceFormatter();
String result = formatter.print(1000, Locale.KOREA);
assertThat(result).isEqualTo("1,000");
}
위 테스트를 통해 parse()와 print()가 잘 작동하는지 확인할 수 있어요.
5. Formatter는 어디서 사용하나요?
ConversionService와 함께 쓰면 더 강력해집니다!
- FormattingConversionService: Formatter + Converter의 기능을 모두 가진 도구입니다.
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addFormatter(new PriceFormatter());
String result = conversionService.convert(10000, String.class);
// result = "10,000"
6. Spring에서 제공하는 기본 Formatter
Spring은 기본적으로 숫자나 날짜를 포맷할 수 있는 Formatter를 제공합니다. 이걸 어노테이션(@) 으로 간편하게 적용할 수 있어요!
대표 어노테이션
어노테이션 설명
| @NumberFormat | 숫자 포맷 지정 |
| @DateTimeFormat | 날짜 포맷 지정 |
예시
@Data
public class FormatForm {
@NumberFormat(pattern = "#,###.##")
private BigDecimal price;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate orderDate;
}
컨트롤러에서 사용하면,
@PostMapping("/format")
public ResponseEntity<String> format(@ModelAttribute FormatForm form) {
return ResponseEntity.ok("가격: " + form.getPrice() + ", 날짜: " + form.getOrderDate());
}
1,000.50 같은 숫자와 2025-06-06 같은 날짜가 제대로 변환되어 들어옵니다!
핵심 요약
개념 설명
| Formatter | 문자열 ↔ 객체 변환, 포맷 제어 |
| parse() | 문자열 → 객체 |
| print() | 객체 → 문자열 |
| Locale | 지역 정보로 포맷 방식 결정 |
| @NumberFormat, @DateTimeFormat | DTO 필드에 포맷 설정 가능 |
| FormattingConversionService | Formatter + Converter 조합 기능 제공 |
'Spring' 카테고리의 다른 글
| JPA 1:N 관계 완전 정리 (0) | 2025.06.09 |
|---|---|
| Spring 데이터 변환 메커니즘 완벽 정리 (0) | 2025.06.06 |
| ConversionService란? (1) | 2025.06.05 |
| TypeConverter — HTTP 요청 문자열을 객체로 편리하게 변환하기 (1) | 2025.06.05 |
| WebMvcConfigurer로 프레임워크 확장하기 (1) | 2025.06.05 |