在springboot应用程序上创建mongobee bean时出错(运行测试时)

时间:2018-10-18 08:33:25

标签: java mongodb spring-boot fongo mongobee

我使用所有鞋帮版本(修复其他问题)

  

mongobee 0.13

     

fongo 2.2.0-RC3-SNAPSHOT

     

mongodb驱动程序3.8.2

运行我的应用程序时,出现此错误:

org.springframework.beans.factory.BeanCreationException:在类路径资源[com / myproject / company / configuration / MongoConfiguration.class]中创建名称为'mongobeeStandalone'的bean时出错:调用init方法失败;嵌套异常是java.lang.AbstractMethodError:com.mongodb.client.internal.FongoOperationExecutor.execute(Lcom / mongodb / operation / ReadOperation; Lcom / mongodb / ReadPreference; Lcom / mongodb / ReadConcern;)Ljava / lang / Object; ...造成原因:java.lang.AbstractMethodError:com.mongodb.client.internal.FongoOperationExecutor.execute(Lcom / mongodb / operation / ReadOperation; Lcom / mongodb / ReadPreference; Lcom / mongodb / ReadConcern;)Ljava / lang / Object ;

我的课:

@Bean
public Mongobee mongobeeStandalone(final MongoTemplate mongoTemplate, final MongoClient mongoClient) {
    final Mongobee runner = new Mongobee(mongoClient);
    runner.setChangeLogsScanPackage(Changelog1.class.getPackage().getName()); // package to scan for changesets
    runner.setDbName(mongoTemplate.getDb().getName());
    return runner;
}

@Bean
public MongoClient mongoClient(final MongoDbFactory mongoDbFactory) {
    final Mongo mongo = mongoDbFactory.getLegacyDb().getMongo();
    if (!MongoClient.class.isInstance(mongo)) {
        throw new UnsupportedOperationException("Must be a MongoClient");
    }
    return MongoClient.class.cast(mongo);
}

编辑

我的测试配置:

@Configuration
public class FoncgoConfiguration extends AbstractMongoConfiguration {

    @Bean
    public Fongo fongo() {
        return new Fongo("mongo-test");
    }

    @Override
    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        final SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(mongoClient(), getDatabaseName());
        final MongoTemplate mongoTemplate = new MongoTemplate(simpleMongoDbFactory, mappingMongoConverter());
        return mongoTemplate;
    }

    @Override
    @Bean
    public MongoClient mongoClient() {
        return MockMongoClient.create(fongo());
    }

}

1 个答案:

答案 0 :(得分:0)

您应该使用Spring Data Mongo,它将创建并注入com.mongodb.MongoClient bean。因此,删除mongoClient()方法并添加Mongodb Spring Data依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Spring Boot还提供了一个MongoTemplate bean并对其进行自动配置。对于测试,您应该使用带有Embedded Mongo批注的@DataMongoTest,因为它配置了MongoTemplate。有关测试示例,请参见here