A Spring MVC web application, noticed all the Spring’s beans are loaded twice!?
1 | package com.mkyong.config.db; |
During Application startup :
1 | 2015-03-0517:52:32 DEBUG c.m.config.MongoLiveConfig- Init...... MongoDbFactory()in production mode! |
1. Spring Configuration
Here is the Spring MVC configuration.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<web-app>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
1 | <beans...> |
2. Solution
Read this Spring DispatcherServlet reference to understand how Spring pick up the XML file :
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and …
In Above Spring configuration :
The servlet mvc-dispatcher will load mvc-dispatcher-servlet.xml
And the listener ContextLoaderListener will loadsmvc-dispatcher-servlet.xml again
To fix it, just renamed the servlet name mvc-dispatcher to something else.
1 | <web-app><!-- Now it will find hello-dispatcher-servlet.xml --> |
In short, make sure Spring will not pick up the Spring XML configuration twice.