前言
- 拦截器中使用@Autowired时为空,这是因为拦截器加载是在Spring Bean创建之前。
public class PermissionInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService; // null
}
- 错误
解决方法
@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 -
﹀
﹀
﹀
梦想是咸鱼
关注一下吧