Spring Boot: Required headers at controller level and error 400 Bad Request instead 404 Not Found
11:52 03 Jul 2026

I have a @RestController that has a required header. If I specify it in the @RequestMapping annotation family, etc.:

@RestController
@RequestMapping("/mycontroller", headers = ["X-Custom-Header"])
class MyController {

  @GetMapping
  fun hello() = "Hello World"
}

If the user doesn't send it, a 404 Not Found error is generated with the message No static resource mycontroller. However, if I specify it as a parameter of the method:

@RestController
@RequestMapping("/mycontroller")
class MyController {

  @GetMapping
  fun hello(
    @RequestHeader("X-Custom-Header") header: String,
  ) = "Hello World"
}

If the user doesn't send it, a 400 Bad Request error is generated with the message Required header 'X-Custom-Header' is not present., which is much more descriptive.

What I'm trying to do is make a header mandatory for all endpoints of the same controller. Ideally, I'd use @RequestMapping because it would only be done once. The value is then retrieved and processed by a @RequestScope bean, so I don't need the values ​​in the endpoints.

An alternative declarative approach is the following, using a method annotated with @ModelAttribute. This still generates a 400 Bad Request error:

@RestController
@RequestMapping("/mycontroller")
class MyController {

  @ModelAttribute
  fun captureHeaders(
    @RequestHeader("X-Custom-Header") header: String,
  ) {
  }

  @GetMapping
  fun hello() = "Hello World"
}

I also know that Filters, HandlerInterceptors, and various hooks exist that are injected in the early stages of requests and allow for checking all of this and generating exceptions, etc., but I'm bringing this up here in case there is a more architectural and declarative way to solve it. I'm sure there are Spring Boot components I'm unaware of that handle these things more concisely.

Thanks for your attention, regards.

spring-boot kotlin http-headers spring-restcontroller request-mapping