在springboot中攔截器Filter中注入bean失敗問題及解決
緣由
在做SSO項目時整合了shiro,在寫一個攔截器的時候(繼承AccessControlFilter)在這里需要注入一個Bean.
按正常的寫法如下:
@Autowired private RedisUtil<Object, Object> redisUtil;
這是我的一個操作redis的工具類。
這樣自動去注入當使用的時候是未NULL,是注入不進去了。
通俗的來講是因為攔截器在spring掃描bean之前加載所以注入不進去。
解決方法
可以通過已經初始化之后applicationContext容器中去獲取需要的bean.
public <T> T getBean(Class<T> clazz,HttpServletRequest request){
WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
return applicationContext.getBean(clazz);
}可以直接調用此方法得到想要的Bean
RedisUtil<String,Object> redisUtil = getBean(RedisUtil.class, request);
這樣就可以直接使用了。
注意*****
如果有其他配置類中有new 一個對象出來,這個對象是不會被springboot管理的,不管你在其他地方用什么方法去交給spring管理創(chuàng)建對象,怎么都會注入為null,所以怎么注入都為null時注意檢查手動new的地方 !!!
錯誤示例
SocketChannelInterceptor 這個對象是不會被spring管理的。
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors( new SocketChannelInterceptor());
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.interceptors( new SocketChannelInterceptor());
}正確示例
@Bean
public SocketChannelInterceptor getSocketChannelInterceptor(){
return new SocketChannelInterceptor();
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors( getSocketChannelInterceptor());
}
@Override
public void configureClientOutboundChannel(ChannelRegistration registration) {
registration.interceptors( getSocketChannelInterceptor());
}總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
bootstrap.yml如何讀取nacos配置中心的配置文件
這篇文章主要介紹了bootstrap.yml讀取nacos配置中心的配置文件問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

