RequestContextHolder.getRequestAttributes()空指针问题

我们都只到RequestContextHolder是Spring提供的可以获取HttpServletRequest的一个工具,于是我在工作中就自己封装了一个工具类如下

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * request上下文工具类
 * 
 * @author chunhui.tan
 * @version 创建时间:2018年10月8日 下午2:48:22
 */
public class HttpContextUtils {

	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static String getDomain() {
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin() {
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}
}

但是在调用这个工具获取HttpServletRequest的时候报了空指针异常,经过排查是RequestContextHolder.getRequestAttributes()获取到的ServletRequestAttributes为null
参照这两篇文章:
SpringMVC之RequestContextHolder分析
spring boot 如何配置RequestContextListener
最后在启动类中加入以下代码即可解决报空指针的问题

@Bean
public RequestContextListener requestContextListener(){
	    return new RequestContextListener();
	} 

你可能感兴趣的:(spring,springboot)