SpringBoot的攔截器中依賴注入為null的解決方法
該項目是基于SpringBoot框架的Maven項目。
今天在攔截器中處理攔截邏輯時需要使用注解調(diào)用其他方法 并且要從配置文件中讀取參數(shù)。所以我使用了以下注解:
@Reference CoreRedisService redisService; @Value("${channel}") private String channel; @Value("${allowMethod}") private String allowMethod;
一個是獲取接口的引用,兩外兩個是獲取配置文件中的參數(shù),
但是在debug過程中發(fā)現(xiàn)三個都沒有注入進來出現(xiàn)了下圖所示的情況:
可以看到三個值都為null。
然后我查看了我項目的配置,確定該攔截器的位置是否在注解的范圍內(nèi)。發(fā)現(xiàn)沒問題, 百度了一下,發(fā)現(xiàn)了有個問題:攔截器加載的時間點在springcontext之前,所以在攔截器中注入自然為null
根據(jù)解決方法在配置攔截器鏈的類中先注入這個攔截器,代碼如下:
package com.***; 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.WebMvcConfigurerAdapter; /** * 配置攔截器鏈 * Created by yefuliang on 2017/10/23. */ @Configuration public class bgqWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean public bgqCommonInterceptorl bgqCommonInterceptorl() { return new bgqCommonInterceptorl(); } public void addInterceptors(InterceptorRegistry registry) { // 多個攔截器組成一個攔截器鏈 // addPathPatterns 用于添加攔截規(guī)則 // excludePathPatterns 用戶排除攔截 registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns("/**"); super.addInterceptors(registry); } }
注意注入的是攔截器類,不是你攔截器里面要注入的類,然后攔截器鏈的 registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns(“/**”);
里面的第一個參數(shù)就不需要你再重新new一個了。
改好之后debug:
可以看到,都注入了進來,問題解決。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot @SpringBootTest加速單元測試的小訣竅
這篇文章主要介紹了SpringBoot @SpringBootTest加速單元測試的小訣竅,具有很好的參考價值,對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11Intellj Idea中的maven工程Java文件顏色不對,未被識別的解決
這篇文章主要介紹了Intellj Idea中的maven工程Java文件顏色不對,未被識別的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08