Spring Boot Java Config 으로 Jackson 설정하기
Spring Boot 에서 Json 을 처리하기 위해 Jackson 라이브러리가 기본적으로 의존성 관계를 가지고 내려받게 되어 있습니다. 이를 Gson 으로바꿔서 사용하는 분들도 계시겠지만, Jackson 은 성능이나 기능에서 훌륭한 편이기 때문에 그대로 사용해도 좋습니다.
Spring Boot 의 application.properties 에서 Jackson 의 설정을 아래와 같이 일부 할 수 있습니다.
[출처] https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.
spring.jackson.default-property-inclusion= # Controls the inclusion of properties during serialization. Configured with one of the values in Jackson's JsonInclude.Include enumeration.
spring.jackson.deserialization.*= # Jackson on/off features that affect the way Java objects are deserialized.
spring.jackson.generator.*= # Jackson on/off features for generators.
spring.jackson.joda-date-time-format= # Joda date time format string. If not configured, "date-format" is used as a fallback if it is configured with a format string.
spring.jackson.locale= # Locale used for formatting.
spring.jackson.mapper.*= # Jackson general purpose on/off features.
spring.jackson.parser.*= # Jackson on/off features for parsers.
spring.jackson.property-naming-strategy= # One of the constants on Jackson's PropertyNamingStrategy. Can also be a fully-qualified class name of a PropertyNamingStrategy subclass.
spring.jackson.serialization.*= # Jackson on/off features that affect the way Java objects are serialized.
spring.jackson.time-zone= # Time zone used when formatting dates. For instance, "America/Los_Angeles" or "GMT+10".
spring.jackson.visibility.*= # Jackson visibility thresholds that can be used to limit which methods (and fields) are auto-detected.
하지만 Java Config 을 이용해서 설정을 직접 정의해줄 수 있습니다. Jackson 을 사용할 때 보통 ObjectMapper 을 생성하여 이를 통해 Json 을 내부적으로 처리하는데, 이 ObjectMapper 을 Spring Bean 으로 등록할 때 기본 설정을 변경할 수 있는 것입니다. 이러한 설정을 위해 Spring 은 Jackson2ObjectMapperBuilder 라는 설정을 위한 Builder 을 제공합니다.
기본적인 방법은 아래와 같습니다.
@Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { return Jackson2ObjectMapperBuilder .json() .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) .modules(new JavaTimeModule()) .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .build(); } }
@Bean 으로 등록되었기 때문에 @Autowired 을 이용해서 주입받아 사용도 가능합니다.
보통 많이 쓰는 용도는 Json 에서 Key 로 Snake Case 로 정의된 것을 Java 의 POJO(Bean) 에서 Camel Case 로 사용하기 위해 명명 전략(propertyNamingStrategy) 을 강제로 등록하거나 날짜 관련 객체와 Json 같의 변환을 위한 다양한 설정 등이 여기서 정의될 수 있습니다.