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

  在SpringMVC項目中咱們通常會引入applicationContext.xml和dispatcher-servlet.xml兩個配置文件,這兩個配置文件具體的區別是什麼呢?web

  Spring 官方文檔介紹以下: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造成了兩個父子關係的上下文。express

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

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

  3)servlet context能夠引用application context裏的實例,反之不能夠。less

  4)多個servlet共享application context裏的實例webapp

  5)在applicationContext和dispatcher-servlet定義的bean最好不要重複,dispatcher-servlet最好只掃描@controler,applicationContext掃描其它spa

     dispatcher-servlet.xmlcode

<context:component-scan base-package="com.test.controller" use-default-filters="false">
  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

    applicationContext.xmlcomponent

<context:component-scan base-package="com.test" use-default-filters="true">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

    注:

      use-default-filters用來指示是否自動掃描帶有@Component、@Repository、@Service和@Controller的類。默認爲true,即默認掃描

      <context:include-filter/>子標籤是用來添加掃描註解

      <context:exclude-filter/>子標籤是用來排除掃描註解

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

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

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

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

<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>
相關文章
相關標籤/搜索