将 Mongeez 与 Spring 引导和 Spring 数据集成 MongoDB

Integrate Mongeez with Spring Boot and Spring Data MongoDB

我想集成 Mongeez with my Spring Boot application and was wondering how to properly run Mongeez during application startup. Mongeez suggests 创建一个 MongeezRunner bean。然而,挑战在于 运行 Mongeez 在任何 Spring 数据初始化发生之前,特别是在创建 MongoTemplate 实例之前。这一点很重要,因为数据库中可能会发生根本阻止应用程序启动的更改(例如,更改索引定义)。

我目前的方法是自己提供 MongoTemplate bean,运行在创建它之前使用 Mongeez:

@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();
}

它有效,但感觉就像一个 hack。还有其他方法吗?

看了Spring Boot 的源代码后,发现这个问题并不是什么新鲜事。例如,FlywayAutoConfiguration 必须确保 Flyway(基于 SQL 的数据库的迁移工具)在创建任何 EntityManagerFactory bean 之前运行。为了实现这一点,自动配置注册了一个 BeanFactoryPostProcessor 动态地使每个 EntityManagerFactory bean 依赖于 Flyway bean,从而强制 Spring 首先创建 Flyway bean。

我通过为 Mongeez 创建一个具有类似自动配置的 Spring 启动器解决了我的问题:mongeez-spring-boot-starter.