获取spring容器中bean的方法

本文介绍了两种在Spring框架中获取Bean的方法:一种是在Web环境中通过`WebApplicationContextUtils.getRequiredWebApplicationContext`方法结合`ServletActionContext.getServletContext()`获取;另一种是通过手动启动Spring容器并加载配置文件来获取Bean。

方案1(Web中使用):

ApplicationContext ct = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
 logService = (ISysLogService) ct.getBean("sysLogServiceImpl");
说明:getRequiredWebApplicationContext方法中需要传入ServletContext()对象,在struts2中可以这样获取:ServletActionContext.getServletContext()

方案2(通过手动启动spring容器后获取,如果在web中,不建议这样使用):

//匹配多个文件

ApplicationContext ct = new FileSystemXmlApplicationContext(new String[] { "classpath:applicationContext.xml","classpath:lb/*/applicationContext-*.xml"});
//加载一个文件

ApplicationContext ct = new FileSystemXmlApplicationContext("classpath:applicationContext.xml");

注:获取spring容器中bean的方法还有几个,这里就不一一列举了,个人认为这两个是最直接最简单的。

转载于:https://my.oschina.net/ht896632/blog/628440

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值