프로젝트 진행 중, 백엔드에서 프론트엔드로 response를 보내줄 때
ResponseEntity가 아닌, 공통된 response 포맷을 만들어서 사용하면 좋겠다라는 피드백을 받았다.
공통 response DTO를 만들어서 사용하면 어떤 이점을 가져갈 수 있을까?
장점
- 일관된 응답 구조
- 모든 API 응답에 동일한 구조를 제공하여 프론트 측에서 데이터를 처리하기 쉽다.
- 유지보수 용이성
- 응답 구조가 변경되어도, 공통 response DTO만 수정하면 모든 관련 API의 응답 구조가 동시에 업데이트 된다.
- 코드를 수정해야 할 범위가 좁아지고, 변경이 쉽다.
- 재사용성 증가
- 제네릭 타입을 <T> 로 사용하면, 다양한 타입과 함께 사용할 수 있다.
사용
SuccessResponse.java
@Getter
@Builder
public class SuccessResponse<T> {
private final String message;
private final T data;
public static <T> SuccessResponse<T> of(String message, T data) {
return SuccessResponse.<T>builder()
.message(message)
.data(data)
.build();
}
}
Controller (Before)
// 휴가 상세 조회
@GetMapping("/{vacationId}")
public ResponseEntity<VacationDetailResponse> getVacationDetail(@PathVariable("vacationId") Long id){
VacationDetailResponse response = vacationService.getVacationDetail(id);
return ResponseEntity.ok(response);
}
Controller (After)
// 휴가 상세 조회
@GetMapping("/{vacationId}")
public SuccessResponse<VacationDetailResponse> getVacationDetail(@PathVariable("vacationId") Long id){
return vacationService.getVacationDetail(id);
}
Service (Before)
//휴가 상세 조회
public VacationDetailResponse getVacationDetail(Long id){
VacationDetailResponse response = vacationRepository.findVacationDetailById(id);
return response
}
Service (After)
//휴가 상세 조회
public SuccessResponse<VacationDetailResponse> getVacationDetail(Long id){
VacationDetailResponse response = vacationRepository.findVacationDetailById(id);
return SuccessResponse.of(
"휴가 상세 조회 성공",
response);
}
Postman - API 테스트 (Before)

Postman - API 테스트 (After)

위와 같이 SuccessResponse 를 응답으로 사용하는 모든 API에서는 이런 일관된 구조로 API응답을 줄 수 있다.
'Spring & Spring Boot' 카테고리의 다른 글
| [Spring] 실시간 채팅 기능 구현(2) - Entity, Controller, Service (8) | 2024.11.12 |
|---|---|
| [Spring] 실시간 채팅 기능 구현(1) - WebSocket, 그리고 STOMP (6) | 2024.11.11 |
| [Spring] JSP vs Thymeleaf (0) | 2024.11.11 |
| [Spring] DTO와 Entity의 분리. 왜? 어떻게? (2) | 2024.11.07 |
| [Spring] DTO vs Entity vs VO (1) | 2024.11.07 |