2023. 1. 8. 03:34ㆍspring
안녕하세요. spring으로 프로젝트를 진행하면서 백엔드 개발자를 준비하고 있는 학생입니다. 공부를 하면서 어노테이션의 역할을 잘 모르고 사용하는 경우가 많아서 제가 이해가 편하도록 정리를 해보려고 합니다. 글을 읽고 나서 잘못된 점이나 부족한 점 댓글로 알려주시면 감사하겠습니다.
Controller란?
클라이언트로 부터 요청을 받은 후 처리하여 응답을 보내주는 역할을 한다.
@Controller의 역할
Model 객체를 만들어 데이터를 담아 뷰를 찾는다.
@RestController의 역할
json 이나 xml 형식으로 http 응답에 담아 보낸다.
@RestController = @Controller + @ResponseBody
의존성 주입하는 방법
생성자 주입을 통해 의존성을 주입하는 방법을 권장하는데 그중 @RequiredArgsConstructor를 사용하는 방법이 좋습니다.
사용방법
@RequiredArgsConstructor
@RestController
public class ItemsController {
private final ItemsService itemService;
}
http 요청을 처리하는 어노테이션 정리
1. GetMapping
조회를 할 때 사용한다.
사용방법
@GetMapping("/api/items/{id}")
public ItemsReadUpdateResponseDto findById(@PathVariable Long id) {
return itemService.findById(id);
}
@PathVariable
url에서 {}안에 들어가는 패스 변수를 넣을 때 사용한다.
2. PostMapping
저장을 할 때 사용한다.
사용방법
@PostMapping("/api/items")
public ItemsReadUpdateResponseDto save(@RequestBody ItemsRequestDto requestDto) {
return itemService.save(requestDto);
}
@RequestBody
httpRequest의 본문 안에 있는 requestbody의 내용을 자바 객체로 맵핑하는 역할을 한다.
3. PutMapping
수정을 할 때 사용한다.
사용방법
@PutMapping("/api/items/{id}")
public ItemsReadUpdateResponseDto update(@PathVariable Long id, @RequestBody ItemsRequestDto requestDto) {
return itemService.update(id, requestDto);
}
4. DeleteMapping
삭제를 할 때 사용한다.
사용방법
@DeleteMapping("/api/items/{id}")
public Long delete(@PathVariable Long id) {
itemService.delete(id);
return id;
}
'spring' 카테고리의 다른 글
| 인텔리제이에서 jdbc 사용시 아이디, 비밀번호 안전하게 넘기는 방법 (0) | 2023.05.23 |
|---|---|
| spring annotation 정리3 @Entity (0) | 2023.01.08 |
| spring annotation 정리2 @Service (0) | 2023.01.08 |
| spring field id doesn't have a default value (0) | 2022.12.18 |