Why is this an issue?

The @PathVariable annotation in Spring extracts values from the URI path and binds them to method parameters in a Spring MVC controller. It is commonly used with @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping to capture path variables from the URI. These annotations map HTTP requests to specific handler methods in a controller. They are part of the Spring Web module and are commonly used to define the routes for different HTTP operations in a RESTful API.

If a method has a path template containing a placeholder, like "/api/resource/{id}", and there’s no @PathVariable annotation on a method parameter to capture the id path variable, Spring will disregard the id variable.

How to fix it

Code examples

Noncompliant code example

@GetMapping("/api/resource/{id}")
public ResponseEntity<String> getResourceById(Long id) { // Noncompliant - The 'id' parameter will not be automatically populated with the path variable value
  return ResponseEntity.ok("Fetching resource with ID: " + id);
}

Compliant solution

@GetMapping("/api/resource/{id}")
public ResponseEntity<String> getResourceById(@PathVariable Long id) { // Compliant
  return ResponseEntity.ok("Fetching resource with ID: " + id);
}

Resources

Documentation

Articles & blog posts