记录贴
要在拦截器注入Service 但注入为null
解决:在配置类修改下就可以了
错误的
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Bean
public HandlerInterceptor getLoginInterceptor(){
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
InterceptorRegistration registration = registry.addInterceptor(new LoginInterceptor());
registration.addPathPatterns("/user/**"); //所有路径都被拦截
registration.excludePathPatterns( //添加不拦截路径
"/login/**", //登录
"/**/*.html", //html静态资源
"/**/*.js", //js静态资源
"/**/*.css" //css静态资源
);
}
正确的
@Configuration
public class LoginConfig implements WebMvcConfigurer {
@Bean
public HandlerInterceptor getLoginInterceptor(){
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//注册拦截器
InterceptorRegistration registration = registry.addInterceptor(getLoginInterceptor());
registration.addPathPatterns("/user/**"); //所有路径都被拦截
registration.excludePathPatterns( //添加不拦截路径
"/login/**", //登录
"/**/*.html", //html静态资源
"/**/*.js", //js静态资源
"/**/*.css" //css静态资源
);
}
别用new 改成方法名就ok了
本文详细解析了在Spring框架中,如何正确地在拦截器(LoginInterceptor)中注入Service,避免注入为null的问题。通过调整配置类LoginConfig的实现方式,使用@Bean注解的方法返回拦截器实例,而非直接new,确保了依赖注入的正确性。

1412

被折叠的 条评论
为什么被折叠?



