spring 动态获取bean

在c/s结构 我们可以通过ApplicationContext的getBean方法来获取bean

例如:

写道
ApplicationContext ctx= new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
 Object obj = ctx.getBean("beanname");

  

而在b/s中我们可以通过WebApplicationContext来获取bean:

实例:首先我们配置spring的log4j级别为DEBUG模式:

log4j.logger.org.springframework=DEBUG

 在web.xml里面配加载项:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

  启动后我们会在控制台看见如下信息:

Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
 Root WebApplicationContext: initialization completed in 1453 ms

 也就是说spring将WebApplicationContext 作为ServletContext 得一个attrubute放在了ServletContext 理参数名为org.springframework.web.context.WebApplicationContext.ROOT。而ServletContext 是application(jvm)级别的,因此我们可以通过servlet的ServletContext 来得到它

 

而获取WebApplicationContext 可以使用WebApplicationContextUtils的方法,此方法需要一个ServletContext 实例作为参数

public static WebApplicationContext getWebApplicationContext(ServletContext sc)

 因此我们可以这样获得我们的bean

WebApplicationContext wb = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object obj = ctx.getBean("beanname");

 跟踪下spring代码:

public static WebApplicationContext getWebApplicationContext(ServletContext sc) {
		return getWebApplicationContext(sc, WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);//实现如下:
	}
public static WebApplicationContext getWebApplicationContext(ServletContext sc, String attrName) {
		Assert.notNull(sc, "ServletContext must not be null");
		Object attr = sc.getAttribute(attrName);
                                return (WebApplicationContext) attr;

end。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值