본문 바로가기

프로그래밍/Spring

[Spring] @RequestMapping, @PostMapping, @GetMapping 차이

(1) 사용 레벨에서 차이

@RequestMapping : 클래스 레벨에서 사용O , 메소드 레벨에서 사용O

@RestController
@RequestMapping("/api")
public class MyController {
   @RequestMapping("/getUser")
   private void getUser(){
      System.out.println("컴파일 에러 없음");
   }
}

 

 

@PostMapping, @GetMapping : 클래스 레벨에서 사용X , 메소드 레벨에서 사용O

@RestController
@PostMapping("/api") //!!!!!이 라인에서 컴파일 에러 발생!!!!!
public class MyController {
   @PostMapping("/getUser")
   private void getUser(){
      System.out.println("컴파일 에러 발생");
   }
}

 

 

(2) 추가적인 각각의 특징

@RequestMapping :  HTTP 요청 방식(GET, POST, PUT, DELETE 등)과 URL 경로, 요청 매개변수, 헤더 등을 기반으로 요청 매핑을 할 수 있습니다. 예를 들어, 다음과 같은 코드를 작성하면 HTTP GET 방식으로 /hello 경로에 대한 요청을 처리할 수 있습니다.

@RequestMapping(value = "/hello", method = RequestMethod.GET)
//@RequestMapping(value = "/hello", method = RequestMethod.POST) 도 가능
//@RequestMapping(value = "/hello", method = RequestMethod.PUT) 도 가능
//@RequestMapping(value = "/hello", method = RequestMethod.DELETE) 도 가능
//..
public String helloWorld() {
   return "Hello World!";
}

 

 

@PostMapping : RequsetBody의 값을 읽을 수 있으나, GET의 경우에는 RequsetBody를 가져올 수 없음

(HTTP POST 요청에 대한 매핑을 정의합니다. 예를 들어, 다음과 같이 코드를 작성하면 HTTP POST 방식으로 /user 경로에 대한 요청을 처리할 수 있습니다. )

@PostMapping("/user")
public User createUser(@RequestBody User user) {
   // User 객체 생성 로직
   return user;
}

 

 

@GetMapping은 HTTP GET 요청에 대한 매핑을 정의합니다. 예를 들어, 다음과 같이 코드를 작성하면 HTTP GET 방식으로 /users/{id} 경로에 대한 요청을 처리할 수 있습니다.

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
   // id에 해당하는 User 객체 반환 로직
   return user;
}

 

 

※ 혹자는 @RequestMapping은 GET과 POST의 URL을 중복으로 선언할 수 없다는데, method에 GET인지, POST 명시하면 문제가 없다

@RestController
public class MyController {
   @RequestMapping(value="/api/getUser", method= RequestMethod.GET)
   private void getUser(){
      System.out.println("GET로 호출시 정상적으로 호출됨");
   }

   @RequestMapping(value="/api/getUser", method= RequestMethod.POST)
   private void getUser2(){
      System.out.println("POST로 호출시 정상적으로 호출됨");
   }
}

 

[요약]

위 차이를 제외하고, 각각의 차이에 대해서 정리하면 아래와 같다. 

@PostMapping과 @GetMapping은 각각 POST와 GET 요청에 대한 매핑을 정의하는데 특화되어 있으며, @RequestMapping은 모든 HTTP 요청 방식에 대한 매핑을 정의할 수 있습니다.

간단히 말하면, @RequestMapping은 모든 요청 방식에 대해 대응할 수 있는 범용적인 어노테이션이고, @PostMapping과 @GetMapping은 각각 POST와 GET 요청에 대한 매핑을 간단하게 정의할 수 있는 특화된 어노테이션입니다.

(@RequestMapping을 사용하면 Swagger에서는 GET, HEAD, POST, PUT, DELETE, OPTION, PATCH를 모두 생성해주지만, @PostMapping은 POST만, @GetMapping은 GET만 생성해준다)

 

[출처]

GPT

https://imucoding.tistory.com/217