springboot拦截器HandlerInterceptor的注入问题 |
您所在的位置:网站首页 › 拦截器运行失败 › 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 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |