Christophe Labouisse bio photo

Christophe Labouisse

Freelance Java expert, Docker enthusiast

Email Twitter Google+ LinkedIn Github Stackoverflow Hopwork

Although MongoDB cannot be actually embedded there is a nice tool mimicking the behavior of an actual embedded database. When writing Spring Boot application it is quite easy to replace the connection to a Mongo server with a connection to an embedded server with a simple configuration file.

The following configuration file should do the trick and will enable you to transparently use an embedded Mongo server instead of connecting to an actual one.

@Configuration
public class TestMongoConfig {
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
@SuppressWarnings("SpringJavaAutowiringInspection")
@Autowired
private MongoProperties properties;
@Autowired(required = false)
private MongoClientOptions options;
@Bean(destroyMethod = "close")
public Mongo mongo() throws IOException {
Net net = mongod().getConfig().net();
properties.setHost(net.getServerAddress().getHostName());
properties.setPort(net.getPort());
return properties.createMongoClient(this.options);
}
@Bean(destroyMethod = "stop")
public MongodProcess mongod() throws IOException {
return mongodExe().start();
}
@Bean(destroyMethod = "stop")
public MongodExecutable mongodExe() throws IOException {
return starter.prepare(mongodConfig());
}
@Bean
public IMongodConfig mongodConfig() throws IOException {
return new MongodConfigBuilder().version(Version.Main.PRODUCTION).build();
}
}