Mongeez Integration with Spring Boot and Spring Data MongoDB

I want to integrate Mongeez with my Spring Boot application and was wondering how to properly start Mongeez during application startup. Mongeez suggests creating a MongeezRunner

bean. However, the challenge is to get Mongeez up and running before any of Spring's initialization takes place, especially before instantiation MongoTemplate

. This is critical because there may be changes in the database that prevent the application from starting at all (such as changing index definitions).

My current approach is to provide the MongoTemplate bean by itself by starting Mongeez before creating it:

@Bean
public MongoTemplate mongoTemplate(Mongo mongo, MongoDbFactory mongoDbFactory,
                                   MongoConverter converter) throws IOException {
    // make sure that Mongeez runs before Spring Data is initialized
    runMongeez(mongo);

    return new MongoTemplate(mongoDbFactory, converter);
}

private void runMongeez(Mongo mongo) throws IOException {
    Mongeez mongeez = new Mongeez();
    mongeez.setMongo(mongo);
    mongeez.setDbName(mongodbDatabaseName);
    mongeez.setFile(new ClassPathResource("/db/migrations.xml"));
    mongeez.process();
}

      

It works, but it looks like a hack. Is there any other way to do this?

+3


source to share


1 answer


Looking at the source code of Spring Boot, it turns out that this problem is nothing new. For example, FlywayAutoConfiguration

must ensure that Flyway (migration tool for SQL-based databases) is executed before any EntityManagerFactory

beans are created. To do this, autoconfiguration registers a BeanFactoryPostProcessor

, which dynamically makes each EntityManagerFactory

bean dependent on the Flyway bean, thereby forcing Spring to create the Flyway bean first.



I solved my problem by creating a Spring boot starter with similar auto-configuration for Mongeez: mongeez-spring-boot-starter .

+8


source







All Articles