【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
2018-10-19 17:21
1141 查看
[code]public class TokenInterceptor implements HandlerInterceptor { @Autowired private ITokenDao tokenDao; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { } ... }
配置信息代码:
[code]@Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { /** * * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TokenInterceptor()) .excludePathPatterns("/user/login"); super.addInterceptors(registry); } }
看似没有问题,但运行结果发现Token拦截器中注入的DAO为null。
原因
造成null的原因是因为拦截器加载是在springcontext创建之前完成的,所以在拦截器中注入实体自然就为null。
解决
解决方法就是让bean提前加载,将配置信息修改为如下:
[code]@Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Bean public HandlerInterceptor getTokenInterceptor(){ return new TokenInterceptor(); } /** * * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getTokenInterceptor()) .excludePathPatterns("/user/login"); super.addInterceptors(registry); } }
重新运行DAO即可注入成功。
阅读更多相关文章推荐
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- 【SpringBoot】拦截器使用@Autowired注入接口为null解决方法
- 解决 SpringMvc 非controller类使用@Autowired注解 service注入为null的问题
- activiti解决实现ExecutionListener spring 自动注入@Autowired为null问题
- 如何解决SpringBoot JpaRepository @Autowired 没法自动注入的问题
- SSM SpringMVC 非Controller类使用@Autowired注解Service为null的解决办法
- 解决非controller使用@Autowired注解注入为null问题
- springboot使用aop拦截controller干一些事导致service们@Autowired全部注入失败
- servlet中利用spring的注解@Autowired自动注入service失败,优雅的解决方法
- 解决非controller使用@Autowired注解注入为null问题
- spring 在Thread中注入@Resource@Autowired失败,总为null~解决
- Springboot ServletContextListener @Autowired null 解决办法
- 因Spring AOP导致@Autowired依赖注入失败的解决方法
- SpringBoot集成Quartz(解决@Autowired空指针Null问题即依赖注入的属性为null)
- Spring 使用注解注入,调用类实例出现 java.lang.NullPointException 问题的解决方法
- 解决Springboot @Autowired 无法注入问题
- Springboot ServletContextListener @Autowired null 解决办法
- [Spring Boot实战系列] - No.4 Spring boot 中如何在Utils类中使用@Autowired注入bean
- 使用反射机制调用service层方法Autowired标签自动注入失败
- Spring用@Autowired注入Map类型Bean时报错解决