您的位置:首页 > 编程语言 > Java开发

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

2017-10-29 23:13 633 查看
http://blog.csdn.net/rnZuoZuo/article/details/22563103?locationNum=15

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

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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: