Two ways of loading spring in web.xml (servlet and listener)

Taken from: http://elfasd.iteye.com/blog/1765939

 

In the actual project, the spring configuration file applicationcontext.xml is automatically loaded into the container through the loading mechanism provided by spring. In the web project, the configuration file is loaded into the web container for parsing. Currently, spring provides two loaders , for the loading of the web container: one is ContextLoaderListener and the other is ContextLoaderServlet. These two are identical in function, except that one is based on the Listener interface newly introduced in Servlet 2.3, and the other is based on the Servlet interface. The following is the timing of these two loaders in web.xml Configure the application:

The first:

<listener>
 <listener-class>org.springframework.context.ContextLoaderListener</listener-class>
</listener>

another:

<servlet>
 <servlet-name>context</servlet-name>
 <servlet-class>org.springframework.context.ContextLoaderServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

Through the above configuration, the web container will automatically load applicationcontext.xml initialization.

If you need to specify the location of the configuration file, you can specify it through context-param:

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/myApplicationContext.xml</param-value>
</context-param>

After that, it is possible to pass

The WebApplicationContextUtils.getWebApplicationContext method gets a reference to the applicationcontext in the web application.

 

In fact, there is also a plugin-based configuration, but it is recommended to use the listener configuration. servlet will no longer be used after 3.0. A basic complete configuration is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 

 <listener>
  <listener-class>
   org.springframework.web.context.ContextLoaderListener
  </listener-class>
 </listener>
 <!--contextConfigLocation在 ContextLoaderListener类中的默认值是 /WEB-INF/applicationContext.xml-->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
  <!-- <param-value>classpath:applicationContext*.xml</param-value> -->
 </context-param>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326926019&siteId=291194637