1、servlet方式加载时:
【web .xml】
- <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/applicationContext</param-value>
- </init-param>
- </servlet>
【jsp/servlet】
- ServletContext context = getServletContext();
- XmlWebApplicationContext applicationContext = (XmlWebApplicationContext)
- context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");
- DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");
2、listener方式加载时:
【web .xml】
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/applicationContext</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
【jsp/servlet】
- ServletContext context = getServletContext();
- WebApplicationContext applicationContext = WebApplicationContextUtils
- .getWebApplicationContext(context);
- DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");
本文深入探讨了使用Spring MVC框架时Servlet和Listener两种加载方式的区别与应用场景,详细解析了如何通过配置web.xml文件实现这两种加载方式,并展示了获取应用上下文和数据源的步骤。

被折叠的 条评论
为什么被折叠?



