在Spring中配置MongoDB时,引用sais:
像这样注册 MongoDB:
@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.
所以 Spring 建议
@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;
}
}
但不幸的是,自 Spring-Data-MongoDB 1.7 以来,MongoFactoryBean 已被弃用并被 MongoClientFactoryBean 取代。
所以
@Bean
public MongoClientFactoryBean mongoClientFactoryBean() {
MongoClientFactoryBean factoryBean = new MongoClientFactoryBean();
factoryBean.setHost("localhost");
return factoryBean;
}
然后是时候配置MongoDbFactory了,它只有一个实现SimpleMongoDbFactory。 SimpleMongoDbFactory 只有两个未弃用的初始化程序,其中之一是 SimpleMongoDbFactory(MongoClient, DataBase)。 但是 MongoClientFactoryBean 只能返回 Mongo 的类型,而不是 MongoClient。
那么,我是否遗漏了一些东西来使这个纯 Spring 配置工作?
最佳答案
是的,它返回一个 Mongo :-(
但是随着 MongoClient 扩展 Mongo 无论如何都可以,只需 @Autowire bean 作为 Mongo
@Autowired
private Mongo mongo;
那就用吧
MongoOperations mongoOps = new MongoTemplate(mongo, "databaseName");
你真的需要 SimpleMongoDbFactory 吗?见 this post .
关于Spring Mongodb : How to configurer mongoDB with MongoClientFactoryBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31537652/