在Servlet(或者Filter,或者Listener)中使用spring的IOC容器

本文介绍了如何在Servlet、Filter或Listener中使用Spring的IOC容器。通过两种方式获取WebApplicationContext对象,一种是直接从ServletContext中获取,另一种是使用WebApplicationContextUtils工具类。需要注意的是,在ServletContextListener中使用时,配置顺序会影响其正确运行。

在servlet或者filter或者Listener中使用spring的IOC容器的方法是:

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:

WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

事实上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代码实现的,建议使用上面上面的静态方法

若是在ServletContextListener(注意不是其他各种Listener)中使用这个这个spring的IOC功能,则注意在web.xml配置文件中该listener应该配置在spring提供的ContextLoaderListener(这个listener是加载spring IOC配置文件)后面,否则会有问题。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值