java.lang.IllegalStateException: No thread-bound request found, exception in aspect

前端 未结 5 1162
不知归路
不知归路 2021-02-02 08:20

Following is my aspect:

    @Configurable
    @Aspect
    public class TimingAspect {

        @Autowired
        private HttpServletRequest httpServletRequest;
         


        
相关标签:
5条回答
  • 2021-02-02 08:55

    Create bean for RequestContextListener. I got the same error for autowiring HttpServletRequest And the following two lines of code works for me

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }
    
    0 讨论(0)
  • 2021-02-02 08:58

    As the error message said: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

    To fix it, register a RequestContextListener listener in web.xml file.

    <web-app ...>
       <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
       </listener>
    </web-app>
    
    0 讨论(0)
  • 2021-02-02 09:02

    With your pointcut expression, you're basically proxying every bean and applying that advice. Some beans exist and operate outside the context of an HttpServletRequest. This means it cannot be retrieved.

    You can only inject the HttpServletRequest in places where a Servlet container request handling thread will pass through.

    0 讨论(0)
  • 2021-02-02 09:06

    You shouldn't autowire a HttpServletRequest in your aspect as this will tie your aspect to be only runnable for classes that are called from within an executing HttpServletRequest.

    Instead use the RequestContextHolder to get the request when you need one.

    private String getRemoteAddress() {
        RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
        if (attribs instanceof NativeWebRequest) {
            HttpServletRequest request = (HttpServletRequest) ((NativeWebRequest) attribs).getNativeRequest();
            return request.getRemoteAddr();
        }
        return null;
    }
    
    0 讨论(0)
  • 2021-02-02 09:13

    @M. Deinum answer doesn't work for me. I use these code instead

    RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
    if (RequestContextHolder.getRequestAttributes() != null) {
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        return request.getRemoteAddr();
    }
    
    0 讨论(0)
提交回复
热议问题