今天遇到这样一个问题,在整合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();
}
}