参考:https://www.2cto.com/database/201608/533434.html
//会忽略 springboot 配置文件里的数据库配置
@Configuration
public class SpringMongoConfig {
public @Bean MongoTemplate mongoTemplate() throws Exception {
//权限验证 MongoCredential
// MongoCredential credential = MongoCredential.createCredential("root", "mydb", "root".toCharArray());
// ServerAddress serverAddress = new ServerAddress("localhost", 27017);
ServerAddress serverAddress = new ServerAddress("192.168.200.100", 27017);
MongoClient mongoClient = new MongoClient(serverAddress);
SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, "yywdb"); // yywdb 是数据库名
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, new MongoMappingContext());
//不插入_class
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory, converter);
return mongoTemplate;
}
}
本文介绍了一个Spring Boot项目中自定义MongoDB配置的方法。通过创建SpringMongoConfig类并使用@Bean注解来实例化MongoTemplate,连接到指定的MongoDB服务器地址(如192.168.200.100:27017),并设置数据库名为yywdb。此外,还展示了如何通过SimpleMongoDbFactory和MappingMongoConverter进行数据库工厂和类型映射配置,以实现MongoDB的数据操作。
1万+

被折叠的 条评论
为什么被折叠?



