如何加载applicationContext?

时间:2016-12-22 13:05:32

标签: java spring-mvc web.xml

web.xml的内容

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/krams/*</url-pattern>
</servlet-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

applicationContext.xml中还有一个WEB.INF文件,但web.xml中没有该文件。怎么加载?

1 个答案:

答案 0 :(得分:0)

ContextLoaderListernerContextLoaderXmlWebApplicationContext类负责加载applicationContext.xml。

请在git上查看他们的源代码。

您会发现ContextLoaderListerner正在延长ContexLoader

ContextLoader文档中,他们提到过:

 * If not explicitly specified, the context implementation is supposed to use a
 * default location (with XmlWebApplicationContext: "/WEB-INF/applicationContext.xml").

这个值在XmlWebApplicationContext中提到如下(如果需要,可以使用其他常量值):

/** Default config location for the root context */
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

/** Default prefix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

/** Default suffix for building a config location for a namespace */
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";

这就是为什么applicationContext.xml文件在web.xml文件中未配置而加载的原因。您需要一些时间来了解Spring使用的所有这些默认配置(魔术)。