How to inject HttpServletRequest into a Spring AOP request (custom scenario)?

前端 未结 1 673
一整个雨季
一整个雨季 2020-12-08 21:44

I know the standard way of writing an AOP advice around a controller method and that you can get access to the HttpServletRequest arg, if declared in controller method.

相关标签:
1条回答
  • 2020-12-08 21:47

    Can I write an aspect around the translation service methods and somehow magically get access to HttpServletRequest regardless of whether it is available in the caller's context or not?

    Not easily. Actually, it would require a lot of effort.

    The easy way to do it is to rely on RequestContextHolder. In every request, the DispatcherServlet binds the current HttpServletRequest to a static ThreadLocal object in the RequestContextHolder. You can retrieve it when executing within the same Thread with

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    

    You can do this in the advice() method and therefore don't need to declare a parameter.

    0 讨论(0)
提交回复
热议问题