1. 전체코드
package jpabook.jpashop.api;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import jpabook.jpashop.domain.Member;
import jpabook.jpashop.service.MemberService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController //data를 바로 json,xml으로 보냄
@RequiredArgsConstructor
public class MemberApiController {
private final MemberService memberService;
@PostMapping("/api/v1/members")
public CreateMemberResponse saveMemberV1(
@RequestBody @Valid Member member) {//json 데이터를 member로 바꿔줘, Member클래스로가서 @들 검증해줘
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
//문제 : 외부에 엔티티 파라미터 노출은 위험, member 변수명 변경시 api 다 터짐
//해결 : DTO
// member 변수명 변경시 컴파일 오류로 알려줌
@PostMapping("/api/v2/members")
public CreateMemberResponse saveMemberV2(
@RequestBody @Valid CreateMemberRequest request) {//json 데이터를 member로 바꿔줘, Member클래스로가서 @들 검증해줘
Member member = new Member();
member.setName(request.getName());
Long id = memberService.join(member);
return new CreateMemberResponse(id);
}
@Data
static class CreateMemberResponse {
private Long id;
public CreateMemberResponse(Long id) {
this.id = id;
}
}
@Data
static class CreateMemberRequest {
@NotEmpty
private String name;
}
}
1.
'Java > Spring-API' 카테고리의 다른 글
회원수정 api 개발 // 500 internal server error 해결방법 (0) | 2023.10.25 |
---|