美文网首页Spring分享技术文技术干货
【SpringBoot】拦截器使用@Autowired注入接口为

【SpringBoot】拦截器使用@Autowired注入接口为

作者: weknow | 来源:发表于2018-03-12 15:33 被阅读35次

最近使用SpringBoot的自定义拦截器,在拦截器中注入了一个DAO,准备下面作相应操作,拦截器代码:

public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private ITokenDao tokenDao;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
     
    }
    
    ...
}

配置信息代码:

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    
    /**
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TokenInterceptor())
                .excludePathPatterns("/user/login");
        super.addInterceptors(registry);
    }

}

看似没有问题,但运行结果发现Token拦截器中注入的DAO为null。

原因

造成null的原因是因为拦截器加载是在springcontext创建之前完成的,所以在拦截器中注入实体自然就为null。

解决

解决方法就是让bean提前加载,将配置信息修改为如下:

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {

    @Bean
    public HandlerInterceptor getTokenInterceptor(){
        return new TokenInterceptor();
    }
    
    /**
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getTokenInterceptor())
                .excludePathPatterns("/user/login");
        super.addInterceptors(registry);
    }

}

重新运行DAO即可注入成功。

相关文章

网友评论

    本文标题:【SpringBoot】拦截器使用@Autowired注入接口为

    本文链接:https://www.haomeiwen.com/subject/yownfftx.html