2024. 12. 9. 21:11ㆍSpring Framework/Spring HATEOAS
🌟 RepresentationModel<T>
란?
Spring HATEOAS(Hypermedia As The Engine Of Application State)는 REST API에서 하이퍼미디어 링크를 추가할 수 있도록 도와주는 라이브러리입니다.RepresentationModel<T>
는 HATEOAS 기능을 활용할 수 있도록 지원하는 기본 클래스입니다.
🔹 주요 역할
✅ REST API 응답에 링크를 추가하여 API 탐색을 용이하게 함
✅ RepresentationModel<T>
를 확장하면 클라이언트가 동적으로 리소스를 탐색 가능
✅ 엔티티를 REST 응답으로 반환할 때 추가적인 링크를 포함하는 방식으로 확장 가능
🎯 RepresentationModel<T>
활용 예제
아래 License
클래스를 통해 RepresentationModel<T>
의 사용법을 알아보겠습니다.
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;
}
📌 설명
License
클래스는RepresentationModel<License>
를 상속하여 HATEOAS 기능을 활용 가능- 일반적인 DTO와 달리, 하이퍼미디어 링크를 추가할 수 있는 기능이 내장됨
License
객체를 JSON으로 변환하면 기본 데이터 외에도 API 탐색을 위한 링크가 포함됨
🛠️ RepresentationModel<T>
활용: 링크 추가하기
🔹 License
객체에 HATEOAS 링크를 추가하는 예제입니다.
1️⃣ LicenseController
에서 License 객체 반환 시 링크 추가
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/licenses")
public class LicenseController {
@GetMapping("/{licenseId}")
public License getLicense(@PathVariable String licenseId) {
License license = new License();
license.setId(1);
license.setLicenseId(licenseId);
license.setDescription("Enterprise License");
license.setOrganizationId("Org123");
license.setProductName("ProductX");
license.setLicenseType("Full");
// 🔗 현재 라이선스의 self 링크 추가
Link selfLink = WebMvcLinkBuilder
.linkTo(methodOn(LicenseController.class).getLicense(licenseId))
.withSelfRel();
license.add(selfLink);
return license;
}
}
📌 설명
methodOn(LicenseController.class).getLicense(licenseId)
를 사용하여 현재 엔드포인트(/licenses/{licenseId}
)에 대한 self 링크를 생성.withSelfRel()
을 사용하여 링크의 관계(Relation)를 "self"로 설정license.add(selfLink);
→RepresentationModel<T>
에서 제공하는add()
메서드를 사용하여 링크를 추가
📡 실제 API 응답(JSON)
위 getLicense()
메서드를 호출하면 아래와 같은 JSON 응답을 받을 수 있습니다.
{
"id": 1,
"licenseId": "L12345",
"description": "Enterprise License",
"organizationId": "Org123",
"productName": "ProductX",
"licenseType": "Full",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L12345"
}
}
}
📌 설명
id
,licenseId
,description
,organizationId
,productName
,licenseType
→ 기존 라이선스 정보_links.self.href
→ 현재 라이선스 정보를 가져올 수 있는 self 링크 추가됨
🎯 EntityModel<T>
vs RepresentationModel<T>
차이점
🔹 EntityModel<T>
와 RepresentationModel<T>
는 모두 HATEOAS 기능을 제공하지만 역할이 다릅니다.
클래스 | 역할 | 특징 |
---|---|---|
RepresentationModel<T> |
리소스에 대한 하이퍼미디어 링크 제공 | 데이터 필드 X, 링크만 포함 가능 |
EntityModel<T> |
엔티티와 링크를 포함하는 래퍼 클래스 | 데이터 필드 O, 엔티티+링크 포함 가능 |
📌 비교 예제
✅ RepresentationModel<T>
사용 예제 (링크만 추가)
public class License extends RepresentationModel<License> {
private int id;
private String licenseId;
}
📌 JSON 응답
{
"_links": {
"self": {
"href": "http://localhost:8080/licenses/1"
}
}
}
✅ EntityModel<T>
사용 예제 (데이터 포함)
import org.springframework.hateoas.EntityModel;
public class LicenseModel extends EntityModel<License> { }
📌 JSON 응답
{
"id": 1,
"licenseId": "L12345",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/1"
}
}
}
📌 정리
RepresentationModel<T>
→ 단순히 링크만 추가 가능EntityModel<T>
→ 데이터와 링크를 함께 포함 가능
🔗 CollectionModel<T>
를 사용하여 리스트 응답 처리
여러 개의 License
객체를 포함하는 리스트 응답을 만들려면 CollectionModel<T>
를 사용합니다.
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.Link;
import java.util.List;
public class LicenseModelList extends CollectionModel<License> {
public LicenseModelList(List<License> licenses, Link link) {
super(licenses, link);
}
}
📌 응답 예시 (JSON)
{
"_embedded": {
"licenses": [
{
"id": 1,
"licenseId": "L12345",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L12345"
}
}
},
{
"id": 2,
"licenseId": "L67890",
"_links": {
"self": {
"href": "http://localhost:8080/licenses/L67890"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/licenses"
}
}
}
📌 설명
_embedded.licenses
→ 여러 개의 라이선스 객체를 포함- 각
License
객체는 개별 self 링크 포함 _links.self.href
→ 전체 라이선스 리스트를 조회할 수 있는 컬렉션 링크 추가
📢 Summary
✅ RepresentationModel<T>
는 HATEOAS 기반 API에서 하이퍼미디어 링크를 추가하기 위한 기본 모델
✅ EntityModel<T>
는 데이터 + 링크를 포함하는 모델
✅ CollectionModel<T>
는 여러 개의 모델을 포함하는 컬렉션 컨테이너
✅ WebMvcLinkBuilder
를 활용하여 동적으로 링크를 생성
이제 RepresentationModel<T>
를 활용하여 더 직관적이고 확장 가능한 REST API를 만들 수 있습니다! 🚀
'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 |
self 링크 (0) | 2024.12.09 |
EntityModel (0) | 2024.12.09 |