標籤:
在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>
applicationContext.xml和dispatcher-servlet.xml的區別