Spring中ApplicationContext載入機制

來源:互聯網
上載者:User

 Spring中ApplicationContext載入機制。
          載入器目前有兩種選擇:ContextLoaderListener和ContextLoaderServlet。
         這兩者在功能上完全等同,只是一個是基於Servlet2.3版本中新引入的Listener介面實現,而另一個基於Servlet介面實現。開發中可根據目標Web容器的實際情況進行選擇。

配置非常簡單,在web.xml中增加:
<listener>
  <listener-class>
       org.springframework.web.context.ContextLoaderListener
  </listener-class>
</listener>
或:
<servlet>
    <servlet-name>context</servlet-name>
    <servlet-class>
       org.springframework.web.context.ContextLoaderServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet> 
 
          通過以上配置,Web容器會自動載入/WEB-INF/applicationContext.xml初始化
ApplicationContext執行個體,如果需要指定設定檔位置,可通過context-param加以指定:
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>

        配置完成之後,即可通過
 WebApplicationContextUtils.getWebApplicationContext方法在Web應用中擷取ApplicationContext引用。

如:ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext();
    LoginAction action=(LoginAction)ctx.getBean("action");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.