Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 Jackson과 함께 @ConstructorProperties 어노테이션을 언제 사용해야 할까?


@ConstructorProperties 어노테이션은 java.beans 패키지에 포함된 표준 어노테이션으로, 어노테이션이 선언된 생성자를 통해 JSON 문자열을 자바 객체로 역직렬화(deserialize)할 때 사용됩니다. 이 기능은 Jackson 2.7 버전부터 지원됩니다.

작동 방식은 매우 단순합니다. 생성자의 각 매개변수마다 일일이 어노테이션을 붙이는 대신, 생성자 매개변수 순서에 대응하는 속성 이름들을 배열 형태로 한 번만 지정하면 됩니다.

주요 사용 사례

이 어노테이션은 특히 setter 메서드가 없는 불변(immutable) 클래스를 다룰 때 유용합니다. 모든 필드가 final로 선언되어 생성자를 통해서만 값을 설정할 수 있는 경우, Jackson이 어떤 JSON 속성이 어떤 생성자 매개변수에 매핑되어야 하는지 판단할 수 있도록 도와줍니다.

참고로 Java 9 이상의 모듈 시스템 환경에서는 java.beans가 java.desktop 모듈에 포함되어 있으므로, 모듈러 애플리케이션에서는 해당 모듈 의존성을 확인해야 합니다.

문법

@Documented
@Target(value=CONSTRUCTOR)
@Retention(value=RUNTIME)
public @interface ConstructorProperties

예제

import com.fasterxml.jackson.databind.ObjectMapper;
import java.beans.ConstructorProperties;

public class ConstructorPropertiesAnnotationTest {
    public static void main(String args[]) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Employee emp = new Employee(115, "Raja");
        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
        System.out.println(jsonString);
    }
}

// Employee 클래스
class Employee {
    private final int id;
    private final String name;

    @ConstructorProperties({"id", "name"})
    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getEmpId() {
        return id;
    }

    public String getEmpName() {
        return name;
    }
}

위 예제에서 Employee 클래스는 필드가 모두 final이며 setter가 없습니다. 하지만 생성자에 @ConstructorProperties({"id", "name"})를 선언했기 때문에, Jackson은 역직렬화 시 첫 번째 매개변수를 'id' 속성에, 두 번째 매개변수를 'name' 속성에 매핑할 수 있습니다.

실행 결과

{
  "empName" : "Raja",
  "empId" : 115
}

직렬화 결과는 getter 메서드 이름(getEmpId(), getEmpName())을 기준으로 속성명이 결정되므로 "empId", "empName"으로 출력됩니다. 반대로 동일한 JSON 구조를 역직렬화할 때는 생성자의 @ConstructorProperties 정보가 활용됩니다.