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

首先看拦截器代码

@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);
    	}
    }

猜你喜欢

转载自blog.csdn.net/qciwyy/article/details/80687955