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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值