Spring MVC – Beans loaded twice

A Spring MVC web application, noticed all the Spring’s beans are loaded twice!?

1
2
3
4
5
6
7
8
9
10
11
12
package com.mkyong.config.db;

@Configuration
publicclass MongoDevConfig {
private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class);

@Bean
MongoDbFactory mongoDbFactory()throws Exception {
//...returnnew new SimpleMongoDbFactory(mongo,"db");;
logger.debug("Init...... MongoDbFactory() in production mode!");
}
}

During Application startup :

1
2
2015-03-0517:52:32 DEBUG c.m.config.MongoLiveConfig- Init...... MongoDbFactory()in production mode!
2015-03-0517:52:32 DEBUG c.m.config.MongoLiveConfig - Init...... MongoDbFactory()in production mode!

1. Spring Configuration

Here is the Spring MVC configuration.

web.xml
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>

mvc-dispatcher-servlet.xml
1
2
3
<beans...>
<context:component-scan base-package="com.springmvc"/><mvc:annotation-driven />
</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.

web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
<web-app><!-- Now it will find hello-dispatcher-servlet.xml -->
<servlet>
<servlet-name>hello-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

In short, make sure Spring will not pick up the Spring XML configuration twice.