1. 程式人生 > >Spring中的applicationContext.xml與SpringMVC的xxx-servlet.xml的區別

Spring中的applicationContext.xml與SpringMVC的xxx-servlet.xml的區別

2個xml檔案的區別

一直搞不明白兩者的區別。
如果使用了SpringMVC,事實上,bean的配置完全可以在xxx-servlet.xml中進行配置。為什麼需要applicationContext.xml?一定必須?

一、
因為直接使用了SpringMVC,所以之前一直不明白xxx-servlet.xml和applicationContext.xml是如何區別的,其實如果直接使用SpringMVC是可以不新增applicationContext.xml檔案的。
使用applicationContext.xml檔案時是需要在web.xml中新增listener的:

org.springframework.web.context.ContextLoaderListener

而這個一般是採用非spring mvc架構,如使用struts之類而又想引入spring才新增的,這個是用來載入Application Context。
如果直接採用SpringMVC,只需要把所有相關配置放到xxx-servlet.xml中就OK了。

二、
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.

雖然現在看的不是很懂,但也是有很大的幫助的