Spring MVC Beans loaded twice
By:Roy.LiuLast updated:2019-08-17
A Spring MVC web application, noticed all the Spring’s beans are loaded twice!?
package com.mkyong.config.db; @Configuration public class MongoDevConfig { private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class); @Bean MongoDbFactory mongoDbFactory() throws Exception { logger.debug("Init...... MongoDbFactory() in production mode!"); //... return new new SimpleMongoDbFactory(mongo, "db");;
During Application startup :
2015-03-05 17:52:32 DEBUG c.m.config.MongoLiveConfig - Init...... MongoDbFactory() in production mode! 2015-03-05 17:52:32 DEBUG c.m.config.MongoLiveConfig - Init...... MongoDbFactory() in production mode!
1. Spring Configuration
Here is the Spring MVC configuration.
web.xml
<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
<beans...> <context:component-scan base-package="com.mkyong" /> <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
<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.
References
- Spring IO : The DispatcherServlet
- StackOverflow : spring web, security + web.xml + mvc dispatcher + Bean is created twice
From:一号门
COMMENTS