Spring Boot 自定义拦截器(HandlerInterceptor)使用@Autowired注入接口为null解决方法
在自定义拦截器代码中使用@Autowired注入CacheService为null
配置信息代码
package com.ding.config;
import com.ding.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
}
}
无注入时没有问题,但有注入运行拦截器中CacheService的结果为null。
造成注入CacheService为null的原因
是因为拦截器加载是在SpringApplicationContext创建之前完成的,所以在拦截器中注入实体CacheService就为null。
解决方法
在MyInterceptor提前加载,配置信息修改如下:
package com.ding.config;
import com.ding.interceptor.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 配置
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Bean
public MyInterceptor getMyInterceptor() {
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**");
}
}
版权声明:本文为weixin_44087826原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。