当前位置: 代码迷 >> Web前端 >> 施用web.xml方式加载Spring时,获取Spring context的两种方式
  详细解决方案

施用web.xml方式加载Spring时,获取Spring context的两种方式

热度:311   发布时间:2012-10-19 16:53:36.0
使用web.xml方式加载Spring时,获取Spring context的两种方式:

1、servlet方式加载时:

web .xml】

?

Xml代码 复制代码
  1. <servlet>??
  2. ????????<servlet-name>dispatcherServlet</servlet-name>??
  3. ????????<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>??
  4. ????????<init-param>??
  5. ????????????<param-name>contextConfigLocation</param-name>??
  6. ????????????<param-value>/WEB-INF/applicationContext</param-value>??
  7. ????????</init-param>??
  8. ????</servlet>??

?

?

【jsp/servlet】

Java代码 复制代码
  1. ServletContext?context?=?getServletContext();? ??
  2. XmlWebApplicationContext?applicationContext?=?(XmlWebApplicationContext) ??
  3. ??
  4. ??
  5. context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet"); ??
  6. ??
  7. ??
  8. ??DataSource?dataSource=(DataSource)applicationContext.getBean("dataSource");??

?

?

?

?

2、listener方式加载时:

web .xml】

?

Java代码 复制代码
  1. <context-param> ??
  2. ??<param-name>contextConfigLocation</param-name> ??
  3. ??<param-value>/WEB-INF/applicationContext</param-value> ??
  4. ?</context-param> ??
  5. ??
  6. <listener> ??
  7. ??<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> ??
  8. ?</listener>??

【jsp/servlet】

?

?

Java代码 复制代码
  1. ServletContext?context?=?getServletContext(); ??
  2. ??
  3. ??? ??
  4. ???WebApplicationContext?applicationContext??=?WebApplicationContextUtils ??
  5. ?????.getWebApplicationContext(context); ??
  6. ??? ??
  7. ??
  8. ??
  9. ??DataSource?dataSource=(DataSource)applicationContext.getBean("dataSource");?
  相关解决方案