SpringBoot Mongo数据源配置

MongoClient配置

1
2
3
4
5
6
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.6.13</version>
<scope>compile</scope>
</dependency>

入口

2.3.7.RELEASE

1
2
3
4
5
6
7
8
9
10
11
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration

@Bean
@ConditionalOnMissingBean(MongoClient.class)
public MongoClient mongo(MongoProperties properties, Environment environment,
ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers,
ObjectProvider<MongoClientSettings> settings) {
return new MongoClientFactory(properties, environment,
builderCustomizers.orderedStream().collect(Collectors.toList()))
.createMongoClient(settings.getIfAvailable());
}

2.6.13

1
2
3
4
5
6
7
8
9
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration

@Bean
@ConditionalOnMissingBean(MongoClient.class)
public MongoClient mongo(ObjectProvider<MongoClientSettingsBuilderCustomizer> builderCustomizers,
MongoClientSettings settings) {
return new MongoClientFactory(builderCustomizers.orderedStream().collect(Collectors.toList()))
.createMongoClient(settings);
}

mongoTemplate配置

1
2
3
4
5
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>

入口

1
2
3
4
5
6
org.springframework.data.mongodb.config.AbstractMongoClientConfiguration

@Bean
public MongoTemplate mongoTemplate(MongoDatabaseFactory databaseFactory, MappingMongoConverter converter) {
return new MongoTemplate(databaseFactory, converter);
}

mongoTemplate自动注入

1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.6.13</version>
</dependency>

入口

1
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration