Spring MVC - Beans chargés deux fois

Spring MVC - Beans chargés deux fois

Une application Web Spring MVC, a remarqué que tous les beans Spring sont chargés deux fois!?

package com.example.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");;

    }

}

Au démarrage de l'application:

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. Configuration du ressort

Voici la configuration Spring MVC.

web.xml



    
        mvc-dispatcher
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    

    
        mvc-dispatcher
        /
    

    
        
            org.springframework.web.context.ContextLoaderListener
        
    

    
        contextConfigLocation
        /WEB-INF/mvc-dispatcher-servlet.xml
    

mvc-dispatcher-servlet.xml



    
    

2. Solution

Lisez ceSpring DispatcherServlet reference pour comprendre comment Spring récupère le fichier XML:

Lors de l'initialisation d'un DispatcherServlet, Spring MVC recherche un fichier nommé [nom-servlet] -servlet.xml dans le répertoire WEB-INF de votre application Web et…

Dans la configuration Above Spring:

  1. Le servletmvc-dispatcher chargeramvc-dispatcher-servlet.xml

  2. Et l'auditeurContextLoaderListener chargera à nouveau `mvc-dispatcher-servlet.xml`

Pour résoudre ce problème, il suffit de renommer le nom du servletmvc-dispatcher en autre chose.

web.xml



    
    
        hello-dispatcher
        
            org.springframework.web.servlet.DispatcherServlet
        
        1
    

    
        hello-dispatcher
        /
    

En bref, assurez-vous que Spring ne récupérera pas la configuration XML de Spring deux fois.