SpringBoot - HandlerInterceptor 中 @Autowired 为空

前言

  • 拦截器中使用@Autowired时为空,这是因为拦截器加载是在Spring Bean创建之前。
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService; // null
    
}
  • 错误
    SpringBoot - HandlerInterceptor 中 @Autowired 为空

解决方法

@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new PermissionInterceptor());
    }
}
  • 修改成:
@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {

    @Bean
    public PermissionInterceptor getPermissionInterceptor() {
        return new PermissionInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getPermissionInterceptor());
    }
}
  • 这样,PermissionInterceptor 由 @Bean 方法生成,其生命周期由 Spring 管理,Spring 将扫描 @Autowired 目标并注入它们。

- End -
梦想是咸鱼
关注一下吧
SpringBoot - HandlerInterceptor 中 @Autowired 为空

SpringBoot - HandlerInterceptor 中 @Autowired 为空

上一篇:《Python Cookbook v3.0.0》Chapter4 迭代器、生成器


下一篇:HashMap 为什么线程不安全?