When configuring MongoDB in Spring, the reference sais:
register MongoDB like this:
@Configuration
public class AppConfig {
/*
* Use the standard Mongo driver API to create a com.mongodb.Mongo instance.
*/
public @Bean Mongo mongo() throws UnknownHostException {
return new Mongo("localhost");
}
}
pollutes the code with the UnknownHostException checked exception. The use of the checked exception is not desirable as Java based bean metadata uses methods as a means to set object dependencies, making the calling code cluttered.
so Spring proposes
@Configuration
public class AppConfig {
/*
* Factory bean that creates the com.mongodb.Mongo instance
*/
public @Bean MongoFactoryBean mongo() {
MongoFactoryBean mongo = new MongoFactoryBean();
mongo.setHost("localhost");
return mongo;
}
}
But unfortunately since Spring-Data-MongoDB 1.7 MongoFactoryBean has been deprecated and replaced by MongoClientFactoryBean.
So
@Bean
public MongoClientFactoryBean mongoClientFactoryBean() {
MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
factoryBean.setHost("localhost");
return factoryBean;
}
Then it's time to configure MongoDbFactory which has only one implementation SimpleMongoDbFactory. The SimpleMongoDbFactory has only two initializer not deprecated one of which is SimpleMongoDbFactory(MongoClient, DataBase). But MongoClientFactoryBean can only return type of Mongo instead of MongoClient.
So, am I missing something to make this pure Spring configuration work?
Yes, DataNucleus JPA allows it, as well as to many other databases.
Interface MongoDbFactory. Deprecated. since 3.0, use MongoDatabaseFactory instead.
It's Easy to Connect MongoDB Atlas with Spring Boot Through this article, we demonstrated that MongoDB Spring Boot integration is easy using: Starter data MongoDB artifactid (the dependency we added while creating the Spring Initializr project) in pom. xml. A property on application.
Yes it returns a Mongo
:-(
But as MongoClient
extends Mongo
that'll be ok anyway, just @Autowire
the bean as a Mongo
@Autowired
private Mongo mongo;
Then use it
MongoOperations mongoOps = new MongoTemplate(mongo, "databaseName");
Do you really need the SimpleMongoDbFactory
? See this post.
In my case, I'm using the following code to create MongoTemplate
. I'm using MongoRespository
. As it only needs MongoTemplate
I need to create the MongoTemplate
bean only.
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoClient mongoClient = new MongoClient("localhost");
MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, "kyc_reader_test");
return new MongoTemplate(mongoDbFactory);
}
In my configuration file, I've added
@EnableMongoRepositories(basePackages = "mongo.repository.package.name")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With