SpringBoot中添加拦截器,在拦截器中注入其他类的时候出现空指针异常解决办法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/QCIWYY/article/details/80687955

首先看拦截器代码

@Component
public class Intercepter extends HandlerInterceptorAdapter{
	
	@Autowired
	public ActionRolesReader actionRolesReader;
	@Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Map<String, String> map = actionRolesReader.GetActionRolesConfig();
		return true;
	}

}

然后注入拦截器

public void addInterceptors(InterceptorRegistry registry) {
    	if(SSOAuth.isEnable=="true") {
    		registry.addInterceptor(new Interceptor())
		            .addPathPatterns("/*")
		            .excludePathPatterns("/")
			        .excludePathPatterns("/search");
		    //registry.addInterceptor(new MyInterceptor_copy()).addPathPatterns("/*");//有多个拦截器继续add进去
		    super.addInterceptors(registry);
    	}
    }

此时运行项目,就会出现空指针异常,为什么会出现这样的问题呢?就是因为我们使用了这段代码

@Autowired
	public ActionRolesReader actionRolesReader;

在引用actionRolesReader时报了空指针,之所以会报空指针就是因为在我们注册拦截器的时候new Interceptor(),不能这样做;

解决办法:使用springmvc的注解方式,将我们编写的拦截器注入进来使用就不会在报空指针异常了。

@Autowired
  public Interceptor interceptor;
  @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	if(SSOAuth.isEnable=="true") {
    		registry.addInterceptor(interceptor)
		            .addPathPatterns("/*")
		            .excludePathPatterns("/")
			        .excludePathPatterns("/search");
		    //registry.addInterceptor(new MyInterceptor_copy()).addPathPatterns("/*");//有多个拦截器继续add进去
		    super.addInterceptors(registry);
    	}
    }

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页