最近使用SpringBoot的自定義攔截器,在攔截器中注入了一個DAO,準備下面做相應操做,攔截器代碼:spring
public class TokenInterceptor implements HandlerInterceptor { @Autowired private ITokenDao tokenDao; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { } ... }
配置信息代碼:ide
@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。spa
緣由code
形成null的緣由是由於攔截器加載是在springcontext建立以前完成的,因此在攔截器中注入實體天然就爲null。blog
解決token
解決方法就是讓bean提早加載,將配置信息修改成以下:get
@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便可注入成功。io