0

I have the following controller:

@RestController
@RequestMapping("/api/{brand}"
public class CarController {

  @GetMapping
  public List<Car> getCars(@PathVariable("brand") String brand) {
    // Some implementation
  }

  @GetMapping("/{model}")
  public Car getCar(@PathVariable("model") String model) {
    // Some implementation
  }

  @PostMapping("/{model}")
  public Car addCar(@PathVariable("model") String model), @RequestBody Car car) {
    // Some implementation
  }
}

And the following RestControllerAdvice:

@RestControllerAdvice(assignableTypes = {CarController.class})
public class InterceptModelPathParameterControllerAdvice {

  @Autowired
  CarService carService;

  @ModelAttribute
  public void validateModel(@PathVariable("model") String model) {
    if (!carService.isSupportedModel(model)) throw new RuntimeException("This model is not supprted by this application.");
  }
}

The validateModel correctly validates the getCar and addCar methods, but it also validates the getCars method. The getCars method does not have a {model} @PathVariable, so a request to this endpoint will always result in a RuntimeException.

Is there any way to exclude a method from being impacted by a ControllerAdvice and ModelAttribute combination?

Titulum
  • 9,928
  • 11
  • 41
  • 79

1 Answers1

0

As far as I have found, there is no real way to exclude a method from being intercepted by the @ModelAttribute in a @ControllerAdvice. You can, however, change the method parameter from @PathVariable("model") String model to HttpServletRequest request and change the implementation as follows:

@ModelAttribute
public void validateModel(HttpServletRequest) {
  Map<String, String> requestAttributes = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
  if (requestAttributes.containsKey("model") {
    String model = requestAttributes.get("model");
    if (!carService.isSupportedModel(model)) throw new RuntimeException("This model is not supprted by this application.");
  }
}
Titulum
  • 9,928
  • 11
  • 41
  • 79