基于SpringBoot拦截器HandlerInterceptor的注入问题

一、问题描述

项目启动后,拦截器下的注入为null,影响拦截器的逻辑操作。如下图:

ACC448F0-4380-24EC-A070-10C50F356471.png

二、解决策略

原因:拦截器加载是在springcontext创建之前完成,详情可以看spring的拦截器加载过程及IOC的关系

解决方案一:使用@Bean在拦截器初始化之前让类加载,重点在于@Bean的拦截器处理及getCheckFilter()的引入

具体如下:

// 拦截器处理
public class CheckFilter implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;
}


// 配置类处理

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Bean
    public CheckFilter getCheckFilter(){
        return  new CheckFilter();
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getCheckFilter()).addPathPatterns("/**").
                excludePathPatterns("/admin/auth/**");
        super.addInterceptors(registry);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/",".jsp");
        super.configureViewResolvers(registry);
    }
}

解决方案二:给拦截器增加配置注解如:@Configuration 、@Component。在配置类中注入,具体如下操作:

// 拦截器处理
@Configuration   //或者 @Component
public class CheckFilter implements HandlerInterceptor {

    @Autowired
    private SystemService systemService;
}


// 配置类处理

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private CheckFilter  checkFilter;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(checkFilter).addPathPatterns("/**").
                excludePathPatterns("/admin/auth/**");
        super.addInterceptors(registry);
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

    @Override
    protected void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/",".jsp");
        super.configureViewResolvers(registry);
    }
}
三、知识总结

1、涉及spring的拦截器加载过程及IOC的管理

2、参考资料SpringBoot的HandlerInterceptor中依赖注入为Null问题

收藏 (0)
评论列表
正在载入评论列表...
我是有底线的
为您推荐
    暂时没有数据