@RequestMapping, @GetMapping, @PostMapping, etc. — Cracked Java
// Spring Framework & Spring Boot · Spring MVC & REST
MidTheoryCoding

@RequestMapping, @GetMapping, @PostMapping, etc.

@GetMapping, @PostMapping, and friends are just @RequestMapping with the HTTP method baked in — composed meta-annotations for readability. They all feed the same RequestMappingHandlerMapping, which builds a RequestMappingInfo from the URL pattern, method, headers, and content types you declare, then matches incoming requests against it.

@RequestMapping — the general form

The original, most flexible annotation. It works at class level (a shared prefix) and method level, and accepts the full set of mapping conditions:

@RequestMapping(
    value = "/api/orders/{id}",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.APPLICATION_JSON_VALUE,
    headers = "X-API-Version=1",
    params = "verbose")
OrderDto get(@PathVariable Long id) { ... }

The composed shortcuts

Spring 4.3+ added method-specific variants. Each is annotated with @RequestMapping(method = …) internally:

  • @GetMappingmethod = GET
  • @PostMappingmethod = POST
  • @PutMappingmethod = PUT
  • @DeleteMappingmethod = DELETE
  • @PatchMappingmethod = PATCH

They expose the same value, produces, consumes, params, headers attributes — only method is fixed.

@RestController
@RequestMapping("/api/orders") // class-level prefix
class OrderController {
    @GetMapping("/{id}")  OrderDto get(@PathVariable Long id) { ... }
    @PostMapping          OrderDto create(@RequestBody CreateOrder c) { ... }
    @DeleteMapping("/{id}") void delete(@PathVariable Long id) { ... }
}

How matching and narrowing work

Class-level paths combine with method-level paths. Among candidates, the mapping with the most specific pattern wins (an exact path beats /{id}). produces is matched against the request's Accept header, consumes against Content-Type — so you can route two methods on the same URL by media type. If a path matches but the method doesn't, Spring returns 405 Method Not Allowed; if consumes doesn't match, 415 Unsupported Media Type.

Mark your status