該項目是基於SpringBoot框架的Maven項目。
今天在攔截器中處理攔截邏輯時需要使用註解調用其他方法並且要從配置文件中讀取參數。所以我使用了以下註解:
@Reference CoreRedisService redisService; @Value("${channel}") private String channel; @Value("${allowMethod}") private String allowMethod;一個是獲取接口的引用,兩外兩個是獲取配置文件中的參數,
但是在debug過程中發現三個都沒有註入進來出現了下圖所示的情況:
可以看到三個值都為null。
然後我查看了我項目的配置,確定該攔截器的位置是否在註解的範圍內。發現沒問題, 百度了一下,發現了有個問題:攔截器加載的時間點在springcontext之前,所以在攔截器中註入自然為null
根據解決方法在配置攔截器鏈的類中先註入這個攔截器,代碼如下:
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. */@Configurationpublic class bgqWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean public bgqCommonInterceptorl bgqCommonInterceptorl() { return new bgqCommonInterceptorl(); } public void addInterceptors(InterceptorRegistry registry) { // 多個攔截器組成一個攔截器鏈// addPathPatterns 用於添加攔截規則// excludePathPatterns 用戶排除攔截registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns("/**"); super.addInterceptors(registry); }}注意注入的是攔截器類,不是你攔截器裡面要注入的類,然後攔截器鏈的registry.addInterceptor(bgqCommonInterceptorl()).addPathPatterns(“/**”);
裡面的第一個參數就不需要你再重新new一個了。
改好之後debug:
可以看到,都注入了進來,問題解決。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。