java.lang.IllegalStateException: No thread-bound request found, exception in aspect
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;
}
@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();
}
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>