//MybatisConfiguration类
@Override
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
if (useDeprecatedExecutor) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new MybatisBatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new MybatisReuseExecutor(this, transaction);
} else {
executor = new MybatisSimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new MybatisCachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
return super.newExecutor(transaction, executorType);
}
这个defaultExecutorType 是Configuration类里的
//Configuration类
protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
为什么写两次一样的
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
总之,这种两次判断的设计是为了增加系统的灵活性、可扩展性和健壮性,确保在不同的情况下都能有一个合适的执行器类型可用。
问:protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;就是这个属性在配置错误的情况下可能没加载上是吧
是的,在某些情况下,即使有protected ExecutorType defaultExecutorType = ExecutorType.SIMPLE;
这样的定义,也可能出现这个属性在配置错误的情况下没有被正确加载的情况。
-
允许外部配置覆盖默认值:
- 首先检查
useDeprecatedExecutor
标志,如果为真,则尝试获取executorType
。这样设计可能是为了在某些情况下,允许外部配置或其他因素来决定执行器类型。 - 进行第一次判断
executorType == null? defaultExecutorType : executorType
,如果外部没有明确指定执行器类型,就使用默认的执行器类型defaultExecutorType
。这提供了一种默认行为,使得在没有特定配置时系统仍能正常运行。 - 第二次判断
executorType == null? ExecutorType.SIMPLE : executorType
是一种备用机制,即使默认执行器类型也没有被设置,仍然可以提供一个保底的执行器类型ExecutorType.SIMPLE
。这种设计增加了系统的灵活性,允许在不同的环境或配置下有不同的执行器选择。
- 首先检查
-
方便未来扩展:
- 这种设计模式为未来的扩展留下了空间。如果以后需要添加更多的执行器类型或者根据不同的条件动态选择执行器类型,这种结构可以更容易地进行扩展和修改。
-
防止意外情况:
- 通过两次判断,可以确保在各种情况下都能有一个明确的执行器类型。如果由于某种原因
defaultExecutorType
没有被正确设置或者出现了意外情况,第二次判断可以提供一个已知的、可靠的备用执行器类型,从而增加了系统的健壮性。 - 可以避免由于执行器类型未正确设置而导致的运行时错误,提高了系统的稳定性。
- 通过两次判断,可以确保在各种情况下都能有一个明确的执行器类型。如果由于某种原因
-
调试和错误排查:
- 在出现问题时,这种结构可以更容易地进行调试和错误排查。开发者可以通过检查这两个判断的结果,确定执行器类型是如何被确定的,以及是否出现了预期之外的情况。