1、servlet方式加载时:
【web .xml】
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>
<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】
Java代码
代码
ServletContext context = getServletContext();
XmlWebApplicationContext applicationContext = (XmlWebApplicationContext)
context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");
DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");
XmlWebApplicationContext applicationContext = (XmlWebApplicationContext)
context.getAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet");
DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");
2、listener方式加载时:
【web .xml】
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>
<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>
Java代码
代码
ServletContext context = getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils
.getWebApplicationContext(context);
DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");
WebApplicationContext applicationContext = WebApplicationContextUtils
.getWebApplicationContext(context);
DataSource dataSource=(DataSource)applicationContext.getBean("dataSource");