Reputation: 2255
Is there any way in spring boot to grab header from request in any point of application? Some static stuff will be great.
Please, be aware that @RequestHeader
does not work for me since I need this value on service layer.
Upvotes: 24
Views: 34655
Reputation: 825
You can inject HttpServletRequest
object in your service layer like this :
@Autowired
HttpServletRequest request;
private void method() {
request.getHeader("headerName");
}
but remember, that bean HttpServletRequest
has HTTP request scope. So, you can't inject that into asynchronous methods etc, because it will throw Runtime Exception
.
hope it helps.
Upvotes: 60
Reputation: 485
I was searching the same question before, i found out that you can use header parameters in the RestController methods with @RequestHeader as you said. So why not direct them into your service layer methods:
@Autowired
ServiceLayerObj serviceLayerObj;
...
@RequestMapping
public YourReturnObj someRestServiceMethod(
@RequestBody SomeObj body,
@RequestHeader(value = "username") String username
){
return serviceLayerObj.yourServiceLayerMethod(body,username);
}
Upvotes: -4