疯狂

STANDING ON THE SHOULDERS OF GIANTS
posts - 481, comments - 486, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

spring 动态获取bean

Posted on 2009-09-01 13:04 疯狂 阅读(4185) 评论(0)  编辑  收藏 所属分类: spring

在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。



只有注册用户登录后才能发表评论。


网站导航: