瘋狂

          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。


          主站蜘蛛池模板: 沧源| 石渠县| 青河县| 恩平市| 湖口县| 嵊泗县| 商丘市| 郓城县| 大邑县| 乐昌市| 古蔺县| 绥宁县| 永善县| 额尔古纳市| 静宁县| 咸阳市| 陆良县| 上高县| 峡江县| 永清县| 金秀| 威远县| 乳山市| 稷山县| 永胜县| 华安县| 鸡泽县| 江西省| 临潭县| 大连市| 卫辉市| 九龙城区| 始兴县| 周至县| 定襄县| 诸城市| 上高县| 佛山市| 富顺县| 咸宁市| 友谊县|