本文分析的是 spring-data-mongodb-1.9.2.RELEASE.jar 和 mongodb-driver-core-3.2.2.jar。

一、UML Class Diagram

核心类是 MongoTemplate,下面这张 UML 类图涉及了主要的类,省略了次要的类。

涉及的类: MongoTemplate,

MongoOperations,

MongoDbFactory,

SimpleMongoDbFactory,

Mongo,

MongoClient,

MongoCredential,

ServerAddress。

二、源码分析

(1) MongoTemplate

MongoTemplate 是 Spring-MongoDB 整合的核心类,它实现了 MongoOperations 接口(该接口定义了 CRUD 操作)。

MongoTemplate 有个核心的构造方法(其他重载的构造方法最终都会调用这个构造方法):

    /**
* Constructor used for a basic template configuration.
*
* @param mongoDbFactory must not be {@literal null}.
* @param mongoConverter
*/
public MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter) { Assert.notNull(mongoDbFactory); this.mongoDbFactory = mongoDbFactory;
this.exceptionTranslator = mongoDbFactory.getExceptionTranslator();
this.mongoConverter = mongoConverter == null ? getDefaultMongoConverter(mongoDbFactory) : mongoConverter;
this.queryMapper = new QueryMapper(this.mongoConverter);
this.updateMapper = new UpdateMapper(this.mongoConverter); // We always have a mapping context in the converter, whether it's a simple one or not
mappingContext = this.mongoConverter.getMappingContext();
// We create indexes based on mapping events
if (null != mappingContext && mappingContext instanceof MongoMappingContext) {
indexCreator = new MongoPersistentEntityIndexCreator((MongoMappingContext) mappingContext, mongoDbFactory);
eventPublisher = new MongoMappingEventPublisher(indexCreator);
if (mappingContext instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) mappingContext).setApplicationEventPublisher(eventPublisher);
}
}
}

可以看到,这个构造方法至少需要一个参数 mongoDbFactory,MongoTemplate 类中其他字段都可以内部构造出来。

(2)MongoDbFactory

MongoDbFactory 是一个接口,用于新建 DB 实例。

它的实现之一是 SimpleMongoDbFactory。

public interface MongoDbFactory {

    /**
* Creates a default {@link DB} instance.
*
* @return
* @throws DataAccessException
*/
DB getDb() throws DataAccessException; /**
* Creates a {@link DB} instance to access the database with the given name.
*
* @param dbName must not be {@literal null} or empty.
* @return
* @throws DataAccessException
*/
DB getDb(String dbName) throws DataAccessException; /**
* Exposes a shared {@link MongoExceptionTranslator}.
*
* @return will never be {@literal null}.
*/
PersistenceExceptionTranslator getExceptionTranslator();
}

(3) SimpleMongoDbFactory

SimpleMongoDbFactory 实现了 MongoDbFactory 接口(以下省略了部分代码):

 public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory {

     private final Mongo mongo;
private final String databaseName;
private final boolean mongoInstanceCreated;
private final UserCredentials credentials;
private final PersistenceExceptionTranslator exceptionTranslator;
private final String authenticationDatabaseName; private WriteConcern writeConcern; /**
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}.
*
* @param uri must not be {@literal null}.
* @throws UnknownHostException
* @since 1.7
*/
public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException {
this(new MongoClient(uri), uri.getDatabase(), true);
} /**
* Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClient}.
*
* @param mongoClient must not be {@literal null}.
* @param databaseName must not be {@literal null}.
* @since 1.7
*/
public SimpleMongoDbFactory(MongoClient mongoClient, String databaseName) {
this(mongoClient, databaseName, false);
} private SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials,
boolean mongoInstanceCreated, String authenticationDatabaseName) { if (mongo instanceof MongoClient && (credentials != null && !UserCredentials.NO_CREDENTIALS.equals(credentials))) {
throw new InvalidDataAccessApiUsageException(
"Usage of 'UserCredentials' with 'MongoClient' is no longer supported. Please use 'MongoCredential' for 'MongoClient' or just 'Mongo'.");
} Assert.notNull(mongo, "Mongo must not be null");
Assert.hasText(databaseName, "Database name must not be empty");
Assert.isTrue(databaseName.matches("[\\w-]+"),
"Database name must only contain letters, numbers, underscores and dashes!"); this.mongo = mongo;
this.databaseName = databaseName;
this.mongoInstanceCreated = mongoInstanceCreated;
this.credentials = credentials == null ? UserCredentials.NO_CREDENTIALS : credentials;
this.exceptionTranslator = new MongoExceptionTranslator();
this.authenticationDatabaseName = StringUtils.hasText(authenticationDatabaseName) ? authenticationDatabaseName
: databaseName; Assert.isTrue(this.authenticationDatabaseName.matches("[\\w-]+"),
"Authentication database name must only contain letters, numbers, underscores and dashes!");
} /**
* @param client
* @param databaseName
* @param mongoInstanceCreated
* @since 1.7
*/
private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) { Assert.notNull(client, "MongoClient must not be null!");
Assert.hasText(databaseName, "Database name must not be empty!"); this.mongo = client;
this.databaseName = databaseName;
this.mongoInstanceCreated = mongoInstanceCreated;
this.exceptionTranslator = new MongoExceptionTranslator();
this.credentials = UserCredentials.NO_CREDENTIALS;
this.authenticationDatabaseName = databaseName;
} }

核心构造方法:

/**
* @param client
* @param databaseName
* @param mongoInstanceCreated
* @since 1.7
*/
private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) { Assert.notNull(client, "MongoClient must not be null!");
Assert.hasText(databaseName, "Database name must not be empty!"); this.mongo = client;
this.databaseName = databaseName;
this.mongoInstanceCreated = mongoInstanceCreated;
this.exceptionTranslator = new MongoExceptionTranslator();
this.credentials = UserCredentials.NO_CREDENTIALS;
this.authenticationDatabaseName = databaseName;
}

第一个参数 MongoClient client(MongoClient): 包含 host, port, username, password 等信息。

(4)MongoClient 与 Mongo

MongoClient 继承了 Mongo。

 /**
* Creates a Mongo instance based on a (single) mongo node using a given ServerAddress and default options.
*
* @param addr the database address
* @param credentialsList the list of credentials used to authenticate all connections
* @param options default options
* @see com.mongodb.ServerAddress
* @since 2.11.0
*/
public MongoClient(final ServerAddress addr, final List<MongoCredential> credentialsList, final MongoClientOptions options) {
super(addr, credentialsList, options);
}

这个核心构造方法接收三个参数:

final ServerAddress addr:可以由 new ServerAddress(host, port) 构造。

final List<MongoCredential> credentialsList: 包含 username, password 等信息。

final MongoClientOptions options: 包含 MongoDB 数据库的配置信息。

(5) MongoCredential

MongoCredential 包含 username, password 等信息。

 public final class MongoCredential {

     private final AuthenticationMechanism mechanism;
private final String userName;
private final String source;
private final char[] password;
private final Map<String, Object> mechanismProperties; // Other code
}

三、其他

Spring-MongoDB 整合与 Spring-MyBatis 相似。

Spring-MyBatis 的核心类是 SqlSessionTemplate,作用与 MongoTemplate 一样。

Spring-MongoDB 关键类的源码分析的更多相关文章

  1. Spring Boot 揭秘与实战 源码分析 - 工作原理剖析

    文章目录 1. EnableAutoConfiguration 帮助我们做了什么 2. 配置参数类 – FreeMarkerProperties 3. 自动配置类 – FreeMarkerAutoCo ...

  2. Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机

    文章目录 1. 开箱即用,内藏玄机 2. 总结 3. 源代码 Spring Boot提供了很多”开箱即用“的依赖模块,那么,Spring Boot 如何巧妙的做到开箱即用,自动配置的呢? 开箱即用,内 ...

  3. Spring Environment(二)源码分析

    Spring Environment(二)源码分析 Spring 系列目录(https://www.cnblogs.com/binarylei/p/10198698.html) Spring Envi ...

  4. JDK中String类的源码分析(二)

    1.startsWith(String prefix, int toffset)方法 包括startsWith(*),endsWith(*)方法,都是调用上述一个方法 public boolean s ...

  5. Spring Security(四) —— 核心过滤器源码分析

    摘要: 原创出处 https://www.cnkirito.moe/spring-security-4/ 「老徐」欢迎转载,保留摘要,谢谢! 4 过滤器详解 前面的部分,我们关注了Spring Sec ...

  6. Set集合架构和常用实现类的源码分析以及实例应用

    说明:Set的实现类都是基于Map来实现的(HashSet是通过HashMap实现的,TreeSet是通过TreeMap实现的). (01) Set 是继承于Collection的接口.它是一个不允许 ...

  7. Spring Cloud Eureka服务注册源码分析

    Eureka是怎么work的 那eureka client如何将本地服务的注册信息发送到远端的注册服务器eureka server上.通过下面的源码分析,看出Eureka Client的定时任务调用E ...

  8. String类的源码分析

    之前面试的时候被问到有没有看过String类的源码,楼主当时就慌了,回来赶紧补一课. 1.构造器(构造方法) String类提供了很多不同的构造器,分别对应了不同的字符串初始化方法,此处从源码中摘录如 ...

  9. Mybatis整合Spring实现事务管理的源码分析

    一:前言 没有完整看完,但是看到了一些关键的地方,这里做个记录,过程会有点乱,以后逐渐补充最终归档为完整流程:相信看过框架源码的都知道过程中无法完全确定是怎样的流程,毕竟不可能全部都去测试一遍 ,但是 ...

随机推荐

  1. ASP.NET Core 2.0 : 六. 举个例子来聊聊它的依赖注入

    本文通过一个维修工与工具库的例子形象的描述一下为什么要用依赖注入.它的工作原理是什么样的, 然后根据这个类比一下ASP.NET Core 中的依赖注入, 从而深刻了解它的使用方法.注意事项以及回收机制 ...

  2. CentOS配置samba服务

    1.服务器需要下载samba.sambaclient包 yum install samba samba-client -y 2.客户端需要下载samba-client.cifs-utils包 yum ...

  3. jquery回调函数的一个案例

    1.引言 今天在学习<jQuery基础教程>在学习编写插件的时候,书中说利用回调函数来当参数,会极大的提高程序的灵活性.对回调函数很陌生.研究了一下给的示例程序.感觉对回调函数有了基本的了 ...

  4. n人围成一圈报数

    题目:有n个人围成一圈,顺序排号.从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来的第几号的那位 思路:用一个数组存这n个人,里面的初始状态全设为1,表示都还在圈子里面. ...

  5. eclipse 精确查询

    ---恢复内容开始--- ctrl+H(一般都是这个,如果无效看你的自定义快捷键) 输入\b 查询的字符串 \b   后面的正则表达式选框必须选

  6. VISUALSVN: UNABLE TO CONNECT TO A REPOSITORY AT URL 无法连接主机的解决办法

    场景:我的系统是win7,安装的 VisualSVN Server 作为svn 服务器,昨天是好的,我手渐,使用鲁大师优化了系统,今天提交,更新的时候,直接提示:Unable to connect t ...

  7. js正则《转载收藏》

    \:转义字符.'\\n'匹配\n ^:开始位置.'^[0-9]'匹配以数字开头的字符,可以匹配'88DC',不可匹配'DC88' $:结束位置.'[0-9]$'匹配以数字结尾的字符,可以匹配'ab12 ...

  8. 如何给自己的外包APP开发报价?

    作者:CODING 兄弟,你看做这样一个软件需要多少钱?" 这估计是所有软件从业人员被问的最多也是最无奈的一个问题.这个问题等同于,"你看装修一个100平米的房子需要多少钱?&qu ...

  9. windows下安装Virtualenvwrapper

    windows下安装Virtualenvwrapper 我们可以使用Virtualenvwrapper来方便地管理python虚拟环境,但是在windows上安装的时候.....直接 install  ...

  10. 自动识别移动端还是PC端

    平时在开发中经常会遇到这样的需求,除了开发PC端之外,还会同时开发移动端.对于简单的页面,可以使用bootstrap之类的框架实现响应式页面,可是当页面很复杂的时候,就需要开发一个移动端页面,一个PC ...