2

In a controller, I can access all the @RequestHeaders using the following code

@RestController
public class MyController {
@RequestMapping(value = "/mypath", method = RequestMethod.GET, produces =   MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity moveEnrollment(@RequestHeader Map<String, String> headers) {
    ..invoke business logic
}
}

How do I inject the headers into a Spring service bean which is not a controller? Otherwise i need to pass on this hashmap all over the place.

I know that I can inject HttpServletRequest and then get the headers but it would be easier if it can be injected directly.

Abe
  • 8,623
  • 10
  • 50
  • 74

1 Answers1

0

What you are missing is that the HttpServletRequest is an instance of one request coming to your web app. It's not a global bean that you can inject in your other classes. It's a new instance with every request. The same goes with your headers, they are only valid in the context of a request. You can't globally inject them anywhere. In your controllers they are passed to your controller methods and as far I as I remember they are not available in your non-controller instances.

There are other types of handlers such as ExceptionHandler and Controller advice that you have access the request in the methods but not on arbitrary classes. It has to be in the context of a request.

Amin J
  • 1,179
  • 9
  • 16
  • 3
    You are actually able to inject the HttpServletRequest anywhere. If the calling thread is part of a http request, its actually that request instance. But its null if the thread is not a request-thread. – Robin Jonsson Sep 16 '16 at 17:50
  • I understand what you are saying but I think what Abe is asking is to inject it in a service rather than methods. And I was explaining that the request is not a global bean but rather is per request. – Amin J Sep 16 '16 at 18:26
  • 1
    @AminJ you can inject httpservletrequest object into a spring service bean. Which is done using threadlocals I guess. So even though the httprequest object is new per request, the bean is injected correctly for that thread. q was whether I could do the same for request headers too. – Abe Sep 16 '16 at 18:40
  • It is recommended to use `RequestContextHolder` over autowiring `HttpServletRequest`. See https://stackoverflow.com/a/24029989/3757139 – Samuel Nov 04 '22 at 16:41