問題:spring框架里面applicationContext.xml 和spring-servlet.xml 的區別
-
在Spring框架中applicationContext.xml和Spring -servlet.xml有任何關系嗎?
-
DispatcherServlet可以使用到在applicationContext.xml中聲明的屬性文件嗎?
-
另外,為什么我需要
*-servlet.xml
呢?為什么只有applicationContext.xml是不夠的?
回答一
Spring允許您在parent-child這個層級結構中定義多個上下文。
applicationContext.xml定義了“root webapp context”的beans,即與webapp關聯的上下文。
spring-servlet.xml(你想叫什么都行)定義了一個servlet的應用程序上下文的bean。在一個webapp(一個Spring servlet)中可能有很多這樣的文件(例如:servlet spring1的spring1 .xml,servlet spring2的spring2 .xml)。
spring-servlet.xml中的bean可以引用applicationContext.xml中的bean,但反之則不行。
所有Spring MVC控制器都必須放在Spring -servlet.xml上下文中。
在大多數簡單的情況下,applicationContext.xml上下文不是必需的。它通常被用于包含webapp中所有servlet共享的bean。如果您只有一個servlet,那么沒有什么意義,除非你有特殊的用處。
回答二
簡單來說就是:
-
applicationContext.xml定義了在所有servlet之間共享的bean。如果您的應用程序有多個servlet,那么在applicationContext.xml中定義共有的資源那就很有用了。
-
spring-servlet.xml定義了只與該servlet相關的bean。這是dispatche servlet。因此,你的Spring MVCcontrollers 必須要在這個文件中定義。
-
如果在web應用程序中只運行一個servlet,那么在spring-servlet.xml里面中定義所有的bean也是沒有問題的鴨。
文章翻譯自Stack Overflow:https://stackoverflow.com/questions/3652090/difference-between-applicationcontext-xml-and-spring-servlet-xml-in-spring-frame