T_era

@RequestMapping 어노테이션 정리 본문

Programing/Spring

@RequestMapping 어노테이션 정리

블스뜸 2025. 5. 6. 16:08

기본 동작 방식

  • Spring Boot 3.0 버전 이하: 명시된 URL 경로(/example)와 해당 경로의 하위 경로(/example/**) 모두 매핑을 허용한다.
  • Spring Boot 3.0 버전 이상 (현재 버전): 명시된 URL 경로(/example)만 매핑을 허용한다.

속성 설정

  • value 속성을 배열 형태로 사용하여 여러 개의 URL 경로를 동시에 매핑할 수 있다.
    • 예시: @RequestMapping({" /example", "/example2", "/example3" })
  • 기본적으로 HTTP Method (POST, GET, PUT, PATCH, DELETE, HEAD) 모두 허용한다.
  • method 속성을 사용하여 특정 HTTP Method만 허용하도록 지정할 수 있다.
@RestController
public class RequestMappingController {

    // HTTP Method는 GET만 허용
    @RequestMapping(value = "/v1", method = RequestMethod.GET)
    public String exampleV1() {
        // 로직 처리
        return "this is sparta!";
    }
}

축약형 어노테이션 (@GetMapping, @PostMapping 등)

  • @GetMapping: @RequestMapping(value = "/경로", method = RequestMethod.GET)과 동일한 역할을 하는 축약형 어노테이션이다.
  • @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping: 각각 POST, PUT, DELETE, PATCH HTTP Method에 대한 @RequestMapping 축약형이다.
  • Spring이 제공하는 어노테이션 내부에 필요한 기능들이 이미 선언되어 있어 편리하게 사용할 수 있다.
  • 일반적으로 @RequestMapping보다는 직관적이고 간결한 축약형 어노테이션을 주로 사용한다.
@RestController
public class RequestMappingController {

    // 모든 HTTP Method 허용
    @GetMapping(value = "/v2")
    public String exampleV2() {
        // 로직 처리
        return "this is sparta!";
    }
}

@RequestMapping의 활용 시점

  • @Target({ElementType.TYPE, ElementType.METHOD}): 클래스 레벨과 메서드 레벨 모두에 적용 가능하다.
  • @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping의 @Target은 ElementType.METHOD이다.
  • @RequestMapping은 주로 클래스 레벨에서 URL의 prefix를 설정하여 Restful API의 계층 구조를 정의할 때 사용된다.
    • 예시: users/{userId}, category/{categoryId}/product/{productId}
@RequestMapping("/prefix")
@RestController
public class RequestMappingController {

    @GetMapping(value = "/v3")
    public String exampleV3() {
        // 로직 처리
        return "this is sparta!";
    }
}
  • 위 예시에서 /prefix는 클래스 레벨에 적용된 prefix이며, /v3는 메서드 레벨에 적용된 경로이다. 따라서 해당 API는 localhost:8080/prefix/v3 URL을 통해 접근할 수 있다.

'Programing > Spring' 카테고리의 다른 글

특정 파라미터 및 헤더 매핑  (0) 2025.05.06
@PathVariable 정리  (0) 2025.05.06
Spring 어노테이션 정리  (0) 2025.05.06
Spring Boot 로깅 및 Controller 어노테이션 요약  (0) 2025.05.06
Spring MVC View Resolver  (1) 2025.05.05