Spring Mongodb: How to configure mongoDB using MongoClientFactoryBean

When configuring MongoDB in Spring, the sais link is:

register MongoDB as follows:

@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 an UnknownHostException exception. Using a checked exception is undesirable because Java bean-based metadata uses methods as a means to set object dependencies, which makes the call code cluttered.

therefore Spring offers

 @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 is deprecated and replaced with 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 of SimpleMongoDbFactory . SimpleMongoDbFactory has only two initializers that are not deprecated, one of which is SimpleMongoDbFactory (MongoClient, DataBase) . But MongoClientFactoryBean can return Mongo type instead of MongoClient .

So, did I miss something to make this clean Spring configuration?

+5
source share
2 answers

Yes, it returns Mongo : - (

But since MongoClient extends Mongo , everything will be fine, just @Autowire bean like Mongo

 @Autowired private Mongo mongo; 

Then use it

 MongoOperations mongoOps = new MongoTemplate(mongo, "databaseName"); 

Do you really need SimpleMongoDbFactory ? See this post .

+4
source

In my case, I use the following code to create MongoTemplate . I am using MongoRespository . Since I only need a MongoTemplate , I only need to create a MongoTemplate bean.

 @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 added

@EnableMongoRepositories(basePackages = "mongo.repository.package.name")

+3
source

All Articles