SpringBoot 中- HandlerInterceptor 中 @Autowired 和 @Resource 为空

今天遇到这样一个问题,在整合jwt 配置拦截器的时候,遇到这样一个问题:

public class JWTInterceptor implements HandlerInterceptor {
    @Autowired
    User user;  //null 

}

解决方法:

错误之前:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JWTInterceptor());
    }
}

修改为:这样,PermissionInterceptor 由 @Bean 方法生成,其生命周期由 Spring 管理,Spring 将扫描 @Autowired 目标并注入它们。

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtInterceptor())
                .excludePathPatterns("/user/**")
                .addPathPatterns("/**");
    }
    @Bean
    public JWTInterceptor jwtInterceptor() {
        return new JWTInterceptor();
    }
}

posted @ 2023-02-13 17:59  wode林夕  阅读(52)  评论(0编辑  收藏  举报  来源