1. 程式人生 > >使用web.xml方式載入Spring時,獲取Spring context的兩種方式

使用web.xml方式載入Spring時,獲取Spring context的兩種方式

 

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