更新时间:2021年02月23日
使用 Spring 的 ContextLoaderListener 加载 Web 应用程序上下文 XML 文件的方法。
方法:在 web.xml 的元素中配置 ContextLoaderListener 。
- ContextLoaderListener 负责加载 contextConfigLoaction servlet 上下文初始化参数指定的根 Web 应用程序上下文 XML 文件。
- <context-param>标签元素指定了 contextConfigLocation servlet 上下文初始化参数。
- 在<param-value>标签元素中可以指定多个值[ classpath*: xml file path ],用逗号隔开。
- 在 web.xml 文件中,标签元素的使用要遵从一定的次序,否则会报异常。
The content of element type "web-app" must match
"(icon?,display-name?,description?,distributable?,context-param*,filter*,filter-mapping*,
listener*,servlet*,servlet-mapping*,session-config?,mime-mapping*,welcome-file-list?,error-page*,
taglib*,resource-env-ref*, resource-ref*,security-constraint*,login-config?,security-role*,
env-entry*,ejb-ref*,ejb-local-ref*)"
配置文件:web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/META-INF/spring/appincationContext.xml</param-value>
</context-param>
<filter>...</filter>
<filter-mapping>...</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/myapp-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
相关书籍:《Spring 学习指南(第四版)》Chapter 12
参考博客:https://www.cnblogs.com/lukelook/p/11071762.html