What is the role of @PathVariable in Spring MVC?

@PathVariable is a Spring MVC annotation that binds a dynamic segment of the request URL to a method parameter. It lets a controller extract identifiers embedded directly in the path rather than relying on query strings.

Key Points: • The URL pattern declares a placeholder in curly braces, such as /users/{userId}, which @PathVariable then maps to a method parameter. • By default, Spring matches the placeholder name to the parameter name, but an explicit name can be given with @PathVariable("userId"). • Multiple path variables can be captured in a single mapping, e.g. /users/{userId}/orders/{orderId}. • Type conversion is automatic, so a placeholder can bind directly to a Long, Integer, or other supported type instead of always being a String. • A missing or unconvertible path variable results in a 4xx error before the handler body even runs.

Example: For a request to GET /users/123, a method mapped to /users/{userId} with a parameter annotated @PathVariable Long userId receives 123 directly, ready to use in a repository lookup.

Code Example:

@GetMapping("/users/{userId}")
public User getUser(@PathVariable Long userId) {
    return userService.findById(userId);
}

Interview Tip: A concise interview answer is:

"@PathVariable extracts a value from a placeholder in the URL pattern and binds it to a method parameter, with automatic type conversion. It's what lets a single mapping like /users/{userId} handle requests for any user ID instead of writing a separate method per ID."