The correct way to load spring configuration file in web.xml

When the ssm framework was integrated, the error that the instance bean was not created has always been reported. I always thought it was the code reason. After repeated testing for a long time, I found out that the reason was that the spring configuration file was not imported correctly. The following figure is an example of my error.

 

The way that web.xml loads the spring configuration file is mainly differentiated according to the name of the configuration file and the location where it is stored. At present, there are mainly two ways.

1. If the name of the spring configuration file is applicationContext.xml and it is stored in the WEB-INF/ directory, then you only need to add the following code to web.xml

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

The listener will automatically scan the applicationContext.xrnl file under WEB-INF/, which is mostly used when there is only one configuration file.
You can also use this special Servlet of Spring's ContextLoaderServlet, the implementation code is as follows

<servlet>
  <servlet-name>context</servlet-name>
  <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-name> 
  <load-on-startup>1 (a smaller number is fine)</load-on-startup>
</servlet>

Both of the above methods can be used, but there are some differences between the two.

2. If the name of the spring configuration file is a custom name, such as applicationContext-test.xml, and it is still stored in the WEB-INF/ directory, then you need to configure the parameter contextConfigLocation, which is a string and listens to The server or servlet will parse the string into multiple files according to specific characters (such as spaces, commas, semicolons). The following code needs to be added:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/application-testA.xml,/WEB-INF/application-testB.xml,/WEB-INF/application-testB.xml</param-value>
</context-param>

If the above is too troublesome, you can use wildcards to abbreviate the above as follows

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

Then add the above listener or servlet code.

3. If there is neither an applicationContext.xml file nor a configuration file identified using the contextConfigLocation parameter, or the configuration file identified by contextConfigLocation does not exist. All will cause Spring to fail to load the configuration file or to create an ApplicationContext instance normally.

 

correct example

 

Reprinted: http://www.cnblogs.com/zjhs/archive/2012/10/26/2741228.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325321570&siteId=291194637