Extracting values from a URL with @PathVariable involves two steps: declaring a placeholder in the mapping annotation's URL pattern, and then binding that placeholder to a method parameter with @PathVariable. Spring handles matching the segment and converting it to the parameter's type.
Key Points: • Placeholders are written in curly braces within the mapping, e.g. @GetMapping("/users/{userId}"). • The method parameter is annotated @PathVariable, and Spring matches it to the placeholder by name automatically if the names line up. • An explicit name can be given with @PathVariable("userId") if the parameter name differs from the placeholder, or when using older Java versions without parameter name retention. • Type conversion happens automatically for common types like Long, Integer, and UUID, so no manual parsing is needed. • Multiple placeholders can appear in the same URL pattern, each captured by its own @PathVariable parameter.
Example: For the mapping @GetMapping("/users/{userId}") with a parameter @PathVariable String userId, a request to /users/123 gives the method the value "123" directly, ready to pass into a service call.
Code Example:
@GetMapping("/users/{userId}")
public User getUser(@PathVariable String userId) {
return userService.findById(userId);
}Interview Tip: A concise interview answer is:
"I declare a placeholder in curly braces inside the mapping, like /users/{userId}, then bind it to a method parameter using @PathVariable, matching by name or with an explicit name if they differ. Spring converts the captured segment to the parameter's type automatically, so I can use it directly, like fetching a user by that ID."