攔截器中注入Feign接口後,報錯NullPointerException

前言

在攔截器中,需要通過Feign調用Auth基礎服務,判斷用戶身份;
此時在Feign Api中出現了NPE錯誤。

正文

之前寫過類似的博客日誌攔截NLP處理,原因主要是:在註冊攔截器時(WebMvcConfig類)直接通過new XXXInterceptor(),並沒有觸發Spring去管理bean,所以@Autowired沒有生效。

在項目中,我使用了主動聲明、手動注入的方法,具體如下:

首先聲明一個utils類,如下

/**
 * @author hpsyche
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    /**
     * 上下文對象實例
     */
    private static ApplicationContext applicationContext;

    @Override
    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtils.applicationContext = applicationContext;
    }

    /**
     * 獲取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    public static Object getBeanByClass(Class clazz){
        return getApplicationContext().getBean(clazz);
    }

}

攔截器的配置:

/**
 * @author Hpsyche
 */
public class GlobalInterceptor implements HandlerInterceptor {

    private IAuthApi iAuthApi= (IAuthApi) SpringContextUtils.getBeanByClass(IAuthApi.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        iAuthApi.doSomething();
    }

}

總結

無。

發佈了68 篇原創文章 · 獲贊 28 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章