SpringBoot拦截器无法注入Service

最近写了一个拦截器,主要是做一个接口调用次数的增量更库。项目启动后,访问请求,报了500,当场炸裂。

先将我写的拦截器代码奉上

public class InterfaceURLInterceptor implements HandlerInterceptor {

    @Autowired
    private ITraDataPublicInfoService service;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 这里写业务逻辑,就不做展示了
        
		// 去库中查询url
        TraDataPublicInfo dataPublicInfo = service.selectByUrl(matchUrl);
        return true;
    }
}

导致500的错误,就是这行代码

TraDataPublicInfo dataPublicInfo = service.selectByUrl(matchUrl);

这里的service为Null了,说明上面使用@Autowired注入失败,为什么呢?

原因:是因为拦截器的加载在springcontext之前,所以自动注入的service是Null

解决办法
在添加拦截器之前用@Bean注解将拦截器注入工厂,接着添加拦截器

我们来看看之前拦截器的配置

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new InterfaceURLInterceptor()).addPathPatterns("/tra/**");
        super.addInterceptors(registry);
    }
}

现在注册到拦截器列队中的方式,是new出来的,我们稍稍做一下修改:

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

	@Bean
    public InterfaceURLInterceptor interfaceURLInterceptor() {
        return new InterfaceURLInterceptor();
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	// 这里不再使用new Intercepter()
    	// 而是上面写的interfaceURLInterceptor()方法
        registry.addInterceptor(interfaceURLInterceptor()).addPathPatterns("/tra/**");
    }
}

这样,问题就解决了~


原创文章,有不足之处还请各路大神多多指点,多多包涵。
如需转载,请标明出处,不胜感激。
                                                                                           —— 码上仙
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值