ITeye博客

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

cysunc · 2008-08-02 02:25 · Spring · Markdown

使用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");

评论(2)

  1. #2 楼 · cysunc · 2008-09-21 14:16

    不好意思,从来没有碰到过你说的这种情况。 因为应用服务器运行正常,在对应的web应用中,调用getServletContext()这个内置方法不应该为null。

  2. #1 楼 · xy_z487 · 2008-09-19 10:00

    2、listener方式加载时: 【jsp/servlet】

    ServletContext context = getServletContext();

    获取的context 为null 从而获取不到 WebApplicationContext applicationContext

    不知道为什么 得到的 servletcontext 为null

评论功能维护中,当前仅展示历史评论。