SpringBoot HandlerInterceptor依賴注入為null
原因
攔截器加載是在springcontext創建之前完成
解決方案
使用@Bean在攔截器初始化之前讓類加載
1.在WebMvcConfigurer的自定義子類加載攔截類,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Configuration public class ApIAppConfigurer implements WebMvcConfigurer { /** * 注入自定義攔截類到spring容器 * @return */ @Bean public ApiInterceptorAdapter getMyInterceptor(){ return new ApiInterceptorAdapter(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getMyInterceptor()) //指定攔截器類 .addPathPatterns( "/api/**" ); //指定該類攔截的url } } |
2.使用@Component把攔截類交與spring容器管理,代碼如下:
1
2
3
4
5
|
@Component public class ApiInterceptorAdapter extends HandlerInterceptorAdapter { @Autowired private IApiTokenService iApiTokenService; } |
3.完成上述兩步就可以通過@Autowired 注入service了。
spring依賴注入對象為null
前不久幫一個同事調試一段代碼,發現注入對象為null
被注解的對象如下
1
2
3
4
5
6
|
@Component public class SparkSource{ @Autowired private SparkConfig sparkConfig ; @Autowired private RedisUtils redisUtils; |
在調用SparkSource時候使用了注入的方式
1
2
3
4
|
@Component public class Owner{ @Autowired private SparkSource sparkSource; |
然后在使用SparkSource 對象的時候一直報null;剛開始以為是注入失敗,斷點調試發現SparkSource對象里面的RedisUtils居然也是為null,說明要不就是注入不成功,要不就是沒有進行初始化。
修改默認構造,啟動日志發現申明bean是成功的。那就是在注入的時候出現了問題,然后一直在Owner里面找原因,留意到其實這個對象本身也是被申明成一個bean組件。
然后跳出Owner,發現其實在他最開始的調用竟然是以new Owner()的方式來獲取對象:
1
|
Owner owner = new Owner(); |
這時候終于找到問題的所在了。修改為:
1
2
|
@Autowired private Owner owner ; |
當對象聲明為bean組件的時候,它是交給spring容器去管理的,容器會幫你進行初始化;但是如果使用new方法來調用對象時,會跳過spring容器生成新的對象,這時候就無法進行初始化,所以在調試的時候就會出現SparkSource對象為null,并且SparkSource對象里面以注入方式引用的對象也為null;被申明為bean對象的組件必須使用注入的方式進行調用。
這是一個spring依賴注入新手很容易忽視的一個問題,一般也不會去重視,希望大家在寫代碼的時候能多加留意。
本文描述可能不夠詳細,大家有空可以去了解一下更多的關于spring依賴注入與控制反轉。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/dengdeng333/article/details/87878882