springboot拦截器HandlerInterceptor的注入问题

一、问题描述

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

二、解决策略

   原因: 拦截器加载是在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、参考资料https://blog.csdn.net/dengdeng333/article/details/87878882

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值