在自定义的HandlerInterceptor中使用@Autowired注入用户服务后,获取其值后发现为null
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
}
原因是在注册AuthenticationInterceptor时使用的是new关键字,没有将其交给Spring进行管理
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 授权拦截
registry.addInterceptor(new AuthenticationInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/login/**","/logout","/chat");
}
那么我们只需要将我们的拦截器交给Spring进行管理
首先在AuthenticationInterceptor上加上@Component注解
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
}
然后在我们的web配置类中注入这个对象,然后用这个对象替换之前用new关键字创建的对象即可
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private AuthenticationInterceptor authenticationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 授权拦截
registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**")
.excludePathPatterns("/login/**","/logout","/chat");
}
}
也可以使用@Bean注解,这样就不需要在AuthenticationInterceptor 上加@Component注解了
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public AuthenticationInterceptor getAuthenticationInterceptor() {
return new AuthenticationInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 授权拦截
registry.addInterceptor(getAuthenticationInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/login/**","/logout","/chat");
}
}