3.5.2 Annotation 기반의 포맷팅
필드 포맷팅은 필드 타입 또는 어노테이션으로 구성될 수 있습니다. 어노테이션을 Formatter에 바인딩하려면, AnnotationFormatterFactory를 구현합니다. 다음 목록은 AnnotationFormatterFactory인터페이스의 정의를 보여줍니다.
package org.springframework.format;
public interface AnnotationFormatterFactory<A extends Annotation> {
Set<Class<?>> getFieldTypes();
Printer<?> getPrinter(A annotation, Class<?> fieldType);
Parser<?> getParser(A annotation, Class<?> fieldType);
}구현을 만들려면 A를 포맷팅 로직과 연결할 필드 annotationType으로 파라미터 화 합니다. (예: org.springframework.format.annotation.DateTimeFormat). getFieldTypes()는 어노테이션이 사용될 수 있는 필드의 타입을 반환합니다. getPrinter()는 annotated된 필드의 값을 프린트하기 위해 Printer를 반환합니다. getParser()는 Parser를 반환하여 annotated된 필드에 대한 clientValue를 Parsing 합니다.

다음 예제 AnnotationFormatterFactory구현은 @NumberFormat어노테이션을 포맷터에 바인드하여 숫자 스타일 또는 패턴을 지정할 수 있도록 합니다.
public final class NumberFormatAnnotationFormatterFactory
implements AnnotationFormatterFactory<NumberFormat> {
public Set<Class<?>> getFieldTypes() {
return new HashSet<Class<?>>(asList(new Class<?>[] {
Short.class, Integer.class, Long.class, Float.class,
Double.class, BigDecimal.class, BigInteger.class }));
}
public Printer<Number> getPrinter(NumberFormat annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation, fieldType);
}
public Parser<Number> getParser(NumberFormat annotation, Class<?> fieldType) {
return configureFormatterFrom(annotation, fieldType);
}
private Formatter<Number> configureFormatterFrom(NumberFormat annotation, Class<?> fieldType) {
if (!annotation.pattern().isEmpty()) {
return new NumberStyleFormatter(annotation.pattern());
} else {
Style style = annotation.style();
if (style == Style.PERCENT) {
return new PercentStyleFormatter();
} else if (style == Style.CURRENCY) {
return new CurrencyStyleFormatter();
} else {
return new NumberStyleFormatter();
}
}
}
}포맷팅을 트리거 하려면 다음 예제와 같이 @NumberFormat으로 필드에 어노테이션을 추가할 수 있습니다.
public class MyModel {
@NumberFormat(style=Style.CURRENCY)
private BigDecimal decimal;
}Format Annotation API
이식 가능한 Format 어노테이션 API는 org.springframework.format.annotation패키지에 있습니다. @NumberFormat을 사용하면 Double, Long및 @DateTimeFormat과 같은 Number필드 뿐만 아니라 java.util.Date, java.util.Calenda, Long(밀리 초 타임 스탬프 용) 및 JSR-310 java.time 및 Joda-Time 값 타입을 포맷 화 할 수 있습니다.
다음 예제에서는 @DateTimeFormat을 사용하여 java.util.Date를 ISO 날짜 (yyyy-MM-dd)로 형식화합니다.
public class MyModel {
@DateTimeFormat(iso=ISO.DATE)
private Date date;
}Last updated
Was this helpful?