spring~ 过滤器中注入bean但是bean为null

博客讲述在过滤器中使用@Autowired注入RedisTemplate时一直为空的问题。解决方式是在过滤器的init()方法中,从servletContext获取ApplicationContext,再获取bean注入。原因猜测是过滤器属tomcat,加Spring注解会生成两个实例,请求进入的实例无法完成注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天在过滤器(@Component注解将过滤器放入spring容器中)中通过@Autowired注入RedisTemplate redisTemplate;时,发现redisTemplate一直为空。

 

先说解决方式:

在过滤器的init()方法中获取servletContext,再从servletContext中获取ApplicationContext,再从ApplicationContext获取bean注入

@Override
public void init(FilterConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();
        XmlWebApplicationContext cxt = (XmlWebApplicationContext) WebApplicationContextUtils.getWebApplicationContext(sc);
        //或者ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);

        if(cxt != null && cxt.getBean("tbUserLoginService") != null &&                                   tbUserLoginService == null){
            tbUserLoginService = (TbUserLoginService) cxt.getBean("tbUserLoginService");
            redisTemplate = (RedisTemplate) cxt.getBean("redisTemplate");
            LOGGER.info("tbUserLoginService 注入");
        }

}

出现问题的原因:

猜测是因为过滤器是属于tomcat的,在filter上加spring的注解是无用的,因为会生成两个该filter的实例A和B(A:tomcat的容器管理,B为spring容器管理)。

A可以读取web.xml中的配置信息,A是没有办法autowired的;B则可以用@autowired注入。但是我们的请求最终进入的是A,所以A中的注入的bean无效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值