Spring Framework中applicationContext.xml和spring-servlet.xml的区别

Spring Framework中applicationContext.xml和spring-servlet.xml的区别

问题描述:

  • applicationContext.xmlspring-servlet.xml 在 Spring Framework 中是否相关?
  • applicationContext.xml 中声明的属性文件是否可用于 DispatcherServlet?
  • 在相关说明中,为什么我需要 *-servlet.xml ?为什么 applicationContext.xml 本身是不够的?
  • Are applicationContext.xml and spring-servlet.xml related anyhow in Spring Framework?
  • Will the properties files declared in applicationContext.xml be available to DispatcherServlet?
  • On a related note, why do I need a *-servlet.xml at all? Why is applicationContext.xml alone insufficient?

Spring 允许您在父子层次结构中定义多个上下文.

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

applicationContext.xml 定义了根 webapp 上下文"的 bean,即与 webapp 关联的上下文.

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

spring-servlet.xml(或任何其他名称)为一个 servlet 的应用程序上下文定义 bean.在一个 webapp 中可以有很多这样的,每个 Spring servlet 一个(例如 spring1-servlet.xml for servlet spring1, spring2-servlet.xml> 用于 servlet spring2).

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).

spring-servlet.xml 中的 bean 可以引用 applicationContext.xml 中的 bean,反之则不行.

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

所有 Spring MVC 控制器都必须进入 spring-servlet.xml 上下文.

All Spring MVC controllers must go in the spring-servlet.xml context.

在大多数简单的情况下,applicationContext.xml 上下文是不必要的.它通常用于包含在 Web 应用程序中的所有 servlet 之间共享的 bean.如果您只有一个 servlet,那么没有什么意义,除非您有特定用途.

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.