Video in progress
What does @RequestMapping on a controller class give you?
@RequestMapping on the class gives a common URL prefix (and produces/consumes if needed) for every method in the controller. The path on the method is appended to it.
📖 Answer
@RestController
@RequestMapping(path = "/api/v1/customers", produces = MediaType.APPLICATION_JSON_VALUE)
class CustomerController {
@GetMapping // GET /api/v1/customers
List<CustomerDto> all() { ... }
@GetMapping("/{id}") // GET /api/v1/customers/{id}
CustomerDto one(@PathVariable Long id) { ... }
@PostMapping("/{id}/block") // POST /api/v1/customers/{id}/block
void block(@PathVariable Long id) { ... }
}
You don't repeat the prefix on every method, and you change the version (/v1) in one place. produces, consumes and headers also apply to every method.
You usually don't put an HTTP method on the class. If you write @RequestMapping(method = GET), it gets added to every method inside, and your POST endpoints unexpectedly stop working.
If two controllers declare the same URL and method, Spring stops at startup with "Ambiguous mapping". That's good: the error doesn't reach prod.
Sign up to mark studied questions and save your progress.