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 합니다.

Ex.

다음 예제 AnnotationFormatterFactory구현은 @NumberFormat어노테이션을 포맷터에 바인드하여 숫자 스타일 또는 패턴을 지정할 수 있도록 합니다.

포맷팅을 트리거 하려면 다음 예제와 같이 @NumberFormat으로 필드에 어노테이션을 추가할 수 있습니다.

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)로 형식화합니다.

Last updated

Was this helpful?