SpringBoot HandlerInterceptor依賴注入為null
原因
攔截器加載是在springcontext創(chuàng)建之前完成
解決方案
使用@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
前不久幫一個(gè)同事調(diào)試一段代碼,發(fā)現(xiàn)注入對象為null
被注解的對象如下
1
2
3
4
5
6
|
@Component public class SparkSource{ @Autowired private SparkConfig sparkConfig ; @Autowired private RedisUtils redisUtils; |
在調(diào)用SparkSource時(shí)候使用了注入的方式
1
2
3
4
|
@Component public class Owner{ @Autowired private SparkSource sparkSource; |
然后在使用SparkSource 對象的時(shí)候一直報(bào)null;剛開始以為是注入失敗,斷點(diǎn)調(diào)試發(fā)現(xiàn)SparkSource對象里面的RedisUtils居然也是為null,說明要不就是注入不成功,要不就是沒有進(jìn)行初始化。
修改默認(rèn)構(gòu)造,啟動日志發(fā)現(xiàn)申明bean是成功的。那就是在注入的時(shí)候出現(xiàn)了問題,然后一直在Owner里面找原因,留意到其實(shí)這個(gè)對象本身也是被申明成一個(gè)bean組件。
然后跳出Owner,發(fā)現(xiàn)其實(shí)在他最開始的調(diào)用竟然是以new Owner()的方式來獲取對象:
1
|
Owner owner = new Owner(); |
這時(shí)候終于找到問題的所在了。修改為:
1
2
|
@Autowired private Owner owner ; |
當(dāng)對象聲明為bean組件的時(shí)候,它是交給spring容器去管理的,容器會幫你進(jìn)行初始化;但是如果使用new方法來調(diào)用對象時(shí),會跳過spring容器生成新的對象,這時(shí)候就無法進(jìn)行初始化,所以在調(diào)試的時(shí)候就會出現(xiàn)SparkSource對象為null,并且SparkSource對象里面以注入方式引用的對象也為null;被申明為bean對象的組件必須使用注入的方式進(jìn)行調(diào)用。
這是一個(gè)spring依賴注入新手很容易忽視的一個(gè)問題,一般也不會去重視,希望大家在寫代碼的時(shí)候能多加留意。
本文描述可能不夠詳細(xì),大家有空可以去了解一下更多的關(guān)于spring依賴注入與控制反轉(zhuǎn)。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/dengdeng333/article/details/87878882