获取spring容器中bean的方法

本文详细介绍了在Web环境中如何使用Spring容器,并通过两种主要方法获取Bean:一种是在ApplicationContext中通过getRequiredWebApplicationContext方法获取,另一种是手动启动Spring容器并使用FileSystemXmlApplicationContext加载配置文件。同时讨论了获取Spring容器中Bean的其他方法,并强调了这两种方式的简便性和适用场景。

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

方案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的方法还有几个,这里就不一一列举了,个人认为这两个是最直接最简单的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值