OneTwo
OneTwo

Reputation: 2483

How can I set global context variables in Spring?

So I have a Spring boot application with many api requests.

For a large number of these requests I know want to log the "user-agent" part of the header from the request.

One solution is to do this.

In my controllers I could just put @RequestHeader("user-agent") String userAgent and pass it on to the service layer to be logged.

But it would be much handier if I could add the user agent as a global variable, just like the username is added as a global variable through the SecurityContextHolder.

So my question is, is it possible to add custom global context variables like the authentication details from the Authentication filter class? And if so how?

Upvotes: 1

Views: 3243

Answers (1)

Akhil Bojedla
Akhil Bojedla

Reputation: 2218

If you are using Spring MVC then you can Autowire HttpServletRequest and get the request headers from it.

@Service
public class HelloService {

    @Autowired
    private HttpServletRequest httpServletRequest;

    public void print() {
        System.out.println(httpServletRequest.getHeader("x-test"));
    }
}

Alternatively you can also get hold of request instance from RequestContextHolder:

((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getHeader("x-test");

Upvotes: 1

Related Questions