applicationContext.xml和dispatcher-servlet.xml的區別


在SpringMVC項目中我們一般會引入applicationContext.xml和dispatcher-servlet.xml兩個配置文件,這兩個配置文件具體的區別是什么呢?

  Spring 官方文檔介紹如下:

    Spring lets you define multiple contexts in a parent-child hierarchy.  
    The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.  
    The spring-servlet.xml (or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml for servlet spring1, spring2-servlet.xml for servlet spring2).  
    Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa.  
    All Spring MVC controllers must go in the spring-servlet.xml context.  
    In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.   

  可見, applicationContext.xml 和 dispatch-servlet.xml形成了兩個父子關系的上下文

  1) 一個bean如果在兩個文件中都被定義了(比如兩個文件中都定義了component scan掃描相同的package), spring會在application context和 servlet context中都生成一個實例,他們處於不同的上下文空間中,他們的行為方式是有可能不一樣的。

  2) 如果在application context和 servlet context中都存在同一個 @Service 的實例, controller(在servlet context中) 通過 @Resource引用時, 會優先選擇servlet context中的實例。

  不過最好的方法是:在applicationContext和dispatcher-servlet定義的bean最好不要重復, dispatcher-servlet最好只是定義controller類型的bean。

  ----------------------------------------------------------------------------------------------------------------------------------------

  ApplicationContext.xml  是spring 全局配置文件,用來控制spring 特性的

  dispatcher-servlet.xml 是spring mvc里面的,控制器、攔截uri轉發view

  使用applicationContext.xml文件時是需要在web.xml中添加listener的:

  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM