applicationContex.xml 和 *-servlet.xml 的区别

来源:互联网 发布:适合程序员的十款壁纸 编辑:程序博客网 时间:2024/06/09 17:18

在spring的开发中经常会遇到这两个配置文件,

那么这两个配置文件究竟有什么区别,为什么有俩,只保留一个行吗,这俩文件的区别在哪呢?

他们之间的配置的参数或者属性有继承关系吗,谁会覆盖谁?

只存在一个配置文件行吗?

带着这个问题 ,我们去问问google, 在stack overflow的网站的专业回答

http://stackoverflow.com/questions/3652090/difference-between-applicationcontext-xml-and-spring-servlet-xml-in-spring-frame


http://www.cnblogs.com/parryyang/p/5783399.html


先说答案

 可见, 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>




顺手翻译一下


Spring lets you define multiple contexts in a parent-child hierarchy.

Spring允许在父子层次中定义多个上下文。

The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.

applicationContext.xml定义了“”“”所有的beans,上下文相关的应用中应用到的所有的beans 按照我个人的理解应该为 service,dao utils 等待这些和 web转发什么没有关联关系的,

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.xmlfor servlet spring1spring2-servlet.xml for servlet spring2).

spring-servlet.xml 定义一个servlet的应用程序上下文的bean。

从这儿可以看出 这个配置文件是给你web相关的程序引用的,也就是说 servlet相关,也就是和web访问相关的 定义

Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa.

这句更明显的说了这个问题,spring-servlet.xml中的bean 可以引用applicationContex.xml中定义的bean, 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.





dispatcher-servlet.xml文件包含所有配置Spring MVC。所以你会发现bean类如viewhandlerresolvers、ConverterFactories、拦截等。所有这些bean是Spring MVC的框架结构,你如何处理Web请求的一部分,提供有用的功能,如数据绑定、角度分辨率和请求映射。





0 0
原创粉丝点击