soominkim Study
article thumbnail
Published 2023. 1. 27. 22:57
[SpringBoot] RESTful 구축 Java/Springboot
728x90

들어가기에 앞서 Record란 불변(Immutable) 데이터 객체를 쉽게 생성할 수 있도록 하는 새로운 유형의 클래스로 JDK14에서 preview로 등장하여 JDK16에서 정식 스펙으로 포함되었다.

 

기존 불변 데이터 객체는 다음과 같다.

public class Person {
    private final String name;
    private final int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
}

상태를 보유하는 불변 객체를 생성하기 위한 많은 코드를 작성했고 모든 필드에 final을 사용하여 명시적으로 정의해야했다. 또한 final를 쓴다고 끝이 아닌 추가적인 작업이 필요했고 이 추가적인 작업들은 아래와 같다.

  • 필드 값을 모두 포함한 생성자
  • 모든 필드에 대한 접근자 메서드
  • 상속을 방지하기 위해 클래스 자체를 final로 선언
  • 로깅 출력을 제공하기 위한 toString 재정의
  • 두 개의 인스턴스를 비교하기 위한 hashCode, equals 재정의

이처럼 많은 추가작업이 필요했던 작업을 보완하기 위해 나온 것이 Record Class이다. 보다 자세한 설명은 하단을 참조하면 된다.

 

[Java] Record Class

Record? 불변(Immutable) 데이터 객체를 쉽게 생성할 수 있도록 하는 새로운 유형의 클래스로 JDK14에서 preview로 등장하여 JDK16에서 정식 스펙에 포함되었다. Record 개념이 등장하기 전에는 불변 데이터

soominkim.tistory.com

 

1. Record Class 생성

package com.sample.model;

public record Greeting(long id, String content) {

}

이 애플리케이션은 Jackson JSON 라이브러를 사용하여 유형의 인스턴스를 GreetingJson으로 자동 마샬링합니다.

Jackson은 기본적으로 웹 스타터에 포함되어 있습니다.

마샬링(Marshalling)은 객체의 메모리 구조를 저장이나 전송을 위해 적당한 자료형태로 변형하는 것을 말한다.

보통 서로 다른 컴퓨터 혹은 서로 다른 프로그램 간에 데이터가 이동되어야 할 경우에 사용된다. 

 

2. Controller 생성

package com.sample.controller;

import org.springframework.web.bind.annotation.RestController;

import com.sample.model.Greeting;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@RestController
public class GteetingController2 {
	private static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting2")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

① 서버를 실행시킨다.

② http://localhost:4040/greeting2로 요청을한다.

③ { "id" : 1,  "content" : "Hello, World!" }가 출력된다.

 

728x90
profile

soominkim Study

@soominkim

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그