拦截器Autowired注入服务(工具类)空指针

代码:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.cache.CacheUtil;

/**
 * 类名: ValidateInterceptor
 * 描述: 校验拦截器
 */
public class ValidateInterceptor implements HandlerInterceptor {

	private static UnLogger logger = UnLogger.getLogger(ValidateInterceptor.class);
	
	@Autowired
	CacheUtil cacheUtil;
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		boolean checkResult=true;
		//指定允许其他域名访问  
		response.addHeader("Access-Control-Allow-Origin", "*");
		//响应类型  响应方法
		response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); 
		response.setHeader("Access-Control-Allow-Headers", "Content-Type");  
		response.addHeader("Access-Control-Max-Age", "30");   
                //省略
		String token = request.getParameter("token");
                //位置1
		//校验
		if(StringUtils.isNotEmpty(token)){
			try{
				if(StringUtils.isNotEmpty(cacheUtil.get(token))){ //报错,空指针异常
					cacheUtil.expire(token, Constant.TOKEN_EFFECTIVE_TIME);
					checkResult = true;
				}
			}catch(Exception e){
				logger.error("redis异常!");
				e.printStackTrace();
				sessionVerify(request, response, checkResult);
			}
		}else{
			sessionVerify(request, response, checkResult);
		}
		return checkResult;
	}
        //省略
}

 

解决办法,在位置1加上下面的代码就可以了:

 

//注入失败
if(cacheClusterUtil == null){
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
	cacheUtil = wac.getBean(CacheUtil.class);
}
引入:
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

 

 

你可能感兴趣的:(Spring,MVC,Spring)