瘋狂

          STANDING ON THE SHOULDERS OF GIANTS
          posts - 481, comments - 486, trackbacks - 0, articles - 1
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          spring 動態獲取bean

          Posted on 2009-09-01 13:04 瘋狂 閱讀(4207) 評論(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。


          主站蜘蛛池模板: 五华县| 高尔夫| 莱西市| 屏东县| 商丘市| 清苑县| 安国市| 龙海市| 福泉市| 疏附县| 望奎县| 许昌市| 筠连县| 荔浦县| 蓬安县| 田东县| 南陵县| 依兰县| 图木舒克市| 忻州市| 滦南县| 汶川县| 汪清县| 青铜峡市| 宾川县| 泰宁县| 陵水| 平原县| 酒泉市| 三门峡市| 富蕴县| 封丘县| 靖边县| 盘锦市| 兴山县| 开封市| 长乐市| 永新县| 广丰县| 建瓯市| 苍山县|