@RequestMapping Vs @GetMapping

πŸ“Œ 1. @RequestMapping

βœ… General-purpose annotation to map any HTTP method (GET, POST, etc.)

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello() {
Β  Β  return "Hello!";
}

πŸ“‹ Syntax:

@RequestMapping(value = "/path", method = RequestMethod.GET)

πŸ”‘ Key Features:

  • Can handle any HTTP verb
  • Supports path, method, params, headers, consumes, produces
  • More verbose but flexible

πŸ“Œ 2. @GetMapping

βœ… A specialized shortcut for @RequestMapping(method = RequestMethod.GET)

@GetMapping("/hello")
public String sayHello() {
Β  Β  return "Hello!";
}

πŸ“‹ Syntax:

@GetMapping("/path")

πŸ”‘ Key Features:

  • Introduced in Spring 4.3
  • Less verbose, cleaner, and more readable
  • Only supports GET requests

πŸ†š Side-by-Side Comparison

Feature @RequestMapping @GetMapping
HTTP Methods Supported All (GET, POST, PUT, DELETE, etc.) Only GET
Verbosity More verbose Concise
Flexibility Highly flexible Use only for GET
Common Use Case Complex mappings, RESTful APIs Simple GET endpoints
Introduced In Early Spring versions Spring 4.3+

βœ… Other Specialized Annotations

Annotation Purpose
@GetMapping For GET requests
@PostMapping For POST requests
@PutMapping For PUT requests
@DeleteMapping For DELETE requests
@PatchMapping For PATCH requests

🎯 Recommendation

βœ… Use @GetMapping, @PostMapping, etc. for cleaner code
βœ… Use @RequestMapping when you need multiple methods or complex conditions

Back to blog

Leave a comment