拦截器中注入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();
    }

}

总结

无。

发布了63 篇原创文章 · 获赞 29 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Hpsyche/article/details/103341194
今日推荐