Spring 5.2 and lower
The @RequestHeader
doesn't provide additional facility to check the value of the parameter to be mandatory i.e. not null.
Given below are the available fields as per Spring Doc
defaultValue
: The default value to use as a fallback.
name
: The name of the request header to bind to.
required
: Whether the header is required; null values are allowed
value
: Alias for name()
So what you can do is read the parameter either with the help of @RequestHeader or inject a HttpServletRequest request, read by request.getHeader(...) and check inside the controller method if the value exists and then can call methods to perform the necessary logic.
Although you can make sure that the parameter exists with the help of required attribute for e.g. @RequestHeader(value = "Authorization", required = true) String authorization)
.
Spring 5.3+
The required
field was tightened up, both the property and the value should exist. From the release notes:
The @RequestHeader annotation detect a null conversion result value and treat it as missing. In order to allow an empty value to be injected as a null argument, either set required=false on the argument annotation, e.g. @RequestParam(required=false), or declare the argument as @Nullable.