self 링크

2024. 12. 9. 21:31Spring Framework/Spring HATEOAS

🌐 Self 링크란?

Self 링크는 RESTful API에서 현재 리소스를 참조하는 자기 자신을 가리키는 하이퍼미디어 링크입니다.
REST API에서 클라이언트가 API 문서를 참조하지 않고도 동적으로 리소스를 탐색할 수 있도록 도와주는 HATEOAS(Hypermedia as the Engine of Application State) 개념의 핵심 요소입니다.

📌 1. Self 링크의 역할

🔹 현재 리소스를 명확하게 참조
🔹 클라이언트가 URL을 직접 구성하지 않아도 API를 사용할 수 있도록 지원
🔹 REST API의 유연성과 유지보수성을 향상
🔹 HATEOAS를 활용한 동적 API 탐색 가능

🎯 2. Self 링크의 특징

특징 설명
📌 현재 리소스를 참조 API 응답에 포함된 링크가 현재 데이터의 위치를 명확하게 가리킴
🛠️ 클라이언트가 동적으로 API를 탐색 문서 없이도 API를 사용할 수 있도록 돕는 하이퍼미디어 원칙 준수
🔗 HATEOAS의 핵심 요소 REST API를 단순한 CRUD 요청에서 벗어나, 동적인 API 탐색 구조를 지원
🔄 API 변경 시 클라이언트 영향 최소화 API 경로가 변경되더라도 클라이언트는 self 링크만 사용하면 됨

🏗 3. Self 링크의 예제 (Spring HATEOAS 적용)

📌 Step 1: Spring Boot 프로젝트에 HATEOAS 의존성 추가 (pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>

spring-boot-starter-hateoas를 추가하면 Spring HATEOAS 기능을 쉽게 활용 가능

📌 Step 2: Self 링크를 포함한 모델 정의

import org.springframework.hateoas.RepresentationModel;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class License extends RepresentationModel<License> {  // ✅ HATEOAS 지원을 위해 RepresentationModel 상속
    private int id;
    private String licenseId;
    private String description;
    private String organizationId;
    private String productName;
    private String licenseType;
}

RepresentationModel<T>를 상속하면 해당 객체에 HATEOAS 링크를 추가할 수 있음

📌 Step 3: Self 링크를 포함하는 컨트롤러 구현

import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "v1/organization/{organizationId}/license")
public class LicenseController {

    @GetMapping(value = "/{licenseId}")
    public ResponseEntity<License> getLicense(
            @PathVariable("organizationId") String organizationId,
            @PathVariable("licenseId") String licenseId) {

        License license = new License();
        license.setId(1);
        license.setLicenseId(licenseId);
        license.setOrganizationId(organizationId);
        license.setDescription("Software Product");
        license.setProductName("Ostock");
        license.setLicenseType("full");

        // ✅ Self 링크 추가
        Link selfLink = WebMvcLinkBuilder.linkTo(
                WebMvcLinkBuilder.methodOn(LicenseController.class)
                        .getLicense(organizationId, licenseId))
                .withSelfRel(); // 현재 리소스에 대한 링크

        license.add(selfLink);  // ✅ Self 링크를 객체에 추가

        return ResponseEntity.ok(license);
    }
}

linkTo()를 사용하여 현재 리소스에 대한 self 링크를 생성
withSelfRel()을 사용하여 해당 링크가 자기 자신을 가리키는 링크임을 명시
license.add(selfLink);를 통해 HATEOAS 링크를 추가

📥 4. Self 링크가 포함된 API 응답 예제

클라이언트가 GET http://localhost:8080/v1/organization/123/license/456 요청을 보냈을 때

{
  "id": 1,
  "licenseId": "456",
  "description": "Software Product",
  "organizationId": "123",
  "productName": "Ostock",
  "licenseType": "full",
  "_links": {
    "self": {
      "href": "http://localhost:8080/v1/organization/123/license/456"
    }
  }
}

"_links" 필드 안에 "self" 링크가 포함됨
"href" 값은 현재 리소스를 참조하는 URL

⚙️ 5. Self 링크 생성 원리

Spring HATEOAS에서 self 링크를 생성하는 흐름을 설명하면:

  1. methodOn() → 컨트롤러의 특정 메서드를 참조하여 URL 템플릿을 생성
    methodOn(LicenseController.class).getLicense(organizationId, licenseId)
  2. linkTo() → 위에서 생성한 URL 템플릿을 기반으로 실제 링크 객체 생성
    linkTo(...)
  3. withSelfRel() → 생성된 링크에 "self" 속성을 부여
    linkTo(...).withSelfRel()
  4. add() → 링크를 RepresentationModel을 상속받은 객체에 추가
    license.add(selfLink);

🔄 6. Self 링크와 다른 링크 비교

링크 유형 설명 예제
Self 링크 현재 리소스를 가리키는 링크 "_links": { "self": { "href": "/org1/lic1" }}
관련 링크 리소스와 관련된 추가 액션을 위한 링크 "_links": { "updateLicense": { "href": "/org1/lic1/update" }}
컬렉션 링크 해당 리소스가 속한 컬렉션(목록)을 가리키는 링크 "_links": { "allLicenses": { "href": "/org1/licenses" }}
컨텍스트 링크 현재 리소스가 속한 부모 리소스를 가리키는 링크 "_links": { "organization": { "href": "/org1" }}

✅ 7. Self 링크의 장점

🔹 1) REST API의 표준 준수

  • RESTful API에서 리소스 탐색성을 높여 REST 원칙에 충실한 설계 가능

🔹 2) 클라이언트의 API 사용 편의성 증가

  • API 변경이 있어도 self 링크를 사용하면 클라이언트가 직접 URL을 수정할 필요 없음

🔹 3) HATEOAS 지원으로 동적 API 탐색 가능

  • 클라이언트가 self 링크를 활용하여 다음 가능한 액션을 동적으로 탐색 가능

🔹 4) API 유지보수성 향상

  • API 변경 시 클라이언트가 영향을 덜 받음

🎉 8. 결론

Self 링크는 RESTful API에서 현재 리소스를 참조하는 중요한 하이퍼미디어 링크
Spring HATEOAS를 사용하면 간단하게 Self 링크를 추가 가능
클라이언트가 문서 없이도 API를 탐색할 수 있도록 돕는 핵심 개념
Self 링크는 REST API의 일관성을 유지하고, HATEOAS를 구현하는 데 필수적인 요소 🚀

'Spring Framework > Spring HATEOAS' 카테고리의 다른 글

HATEOAS(Hypermedia as the Engine of Application State)  (0) 2025.03.03
WebMvcLinkBuilder  (0) 2024.12.11
_links  (0) 2024.12.11
EntityModel  (0) 2024.12.09
RepresentationModel  (0) 2024.12.09