zl程序教程

您现在的位置是:首页 >  后端

当前栏目

spring boot项目中handlerinterceptor autowired 为空解决办法

SpringBoot项目 解决办法 为空 Autowired
2023-06-13 09:15:57 时间

在我们使用拦截器的时候,有时候需要使用bean对象,这个时候,如果我们直接使用了@autowired或者是@Resource注解的的时候,发现对象为空。是什么原因导致的呢?

无注入时没有问题,但有注入运行拦截器中CacheService的结果为null。

造成注入CacheService为null的原因

是因为拦截器加载是在SpringApplicationContext创建之前完成的,所以在拦截器中注入实体CacheService就为null。

知道了问题出现的原因,那么解决办法有两种情况:

1:直接通过springApplicatinContext的getBean方法。如下图:

ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
//这种方式获取
cacheUtils = (CacheUtils) ac1.getBean("cacheUtils");

2:通过spring boot的方法,配置成bean,然后通过bean方式注入: