How does @PathVariable interact with other request mappings?

@PathVariable works together with mapping annotations like @RequestMapping, @GetMapping, and others by extracting dynamic segments from the same URL pattern those annotations declare. The mapping annotation defines where the placeholder sits in the path, and @PathVariable pulls its value into the handler method.

Key Points: • The placeholder syntax {name} used in @GetMapping or @RequestMapping is exactly what @PathVariable binds to. • A single mapping can combine multiple path variables with query parameters (@RequestParam) and a request body (@RequestBody) in one method signature. • Class-level @RequestMapping base paths can also contain path variables that are still accessible in method parameters. • Regex constraints can be added inside the placeholder, e.g. {id:[0-9]+}, to restrict what the mapping matches before @PathVariable even runs. • If a mapping's placeholder name doesn't match the parameter name, an explicit @PathVariable("name") is required to avoid a binding error.

Example: A method mapped with @GetMapping("/orders/{orderId}/items/{itemId}") can declare both @PathVariable Long orderId and @PathVariable Long itemId, letting one handler serve any combination of order and item IDs.

Code Example:

@GetMapping("/orders/{orderId}/items/{itemId}")
public Item getItem(@PathVariable Long orderId, @PathVariable Long itemId) {
    return orderService.findItem(orderId, itemId);
}

Interview Tip: A concise interview answer is:

"@PathVariable pairs directly with the placeholders declared in @RequestMapping or @GetMapping — the mapping defines the URL pattern, and @PathVariable extracts the matching segments into method parameters. You can combine several path variables with query parameters or a request body in the same handler."