springboot拦截器@Autowired 注入时为null问题解决

最近在使用拦截器验证token时,@Autowired注入为null。
在这里插入图片描述
在这里插入图片描述
导入的Dao为null,没有生效,可以用以下方法解决。

通过给方法添加 @Bean 注解,返回一个 LoginHandlerInterceptor 的 Bean,该 loginHandlerInterceptor 就可以正常的使用 @autowired 了。

在这里插入图片描述
在这里插入图片描述
整合起来就是这样:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
//在SpringBoot2.0及Spring 5.0中WebMvcConfigurerAdapter已被废弃,直接实现WebMvcConfigurer

    @Bean
    public LoginHandlerInterceptor loginHandlerInterceptor() {
    
        return new LoginHandlerInterceptor();
        
    }
    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
    
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
        
            //注册拦截器
            @Override
           public void addInterceptors(InterceptorRegistry registry) {
           
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(loginHandlerInterceptor()).addPathPatterns("/**");
                
            }
        };
        return adapter;
    }

}

结果
在这里插入图片描述
注入成功,显示结果。希望对大家有帮助。

发布了4 篇原创文章 · 获赞 3 · 访问量 2165

猜你喜欢

转载自blog.csdn.net/weixin_43285123/article/details/102814149