mybatis 架构及基础模块
1、 mybatis整体架构

基础支撑层详解
1、日志模块
mybatis日志模块没有实现类,需要接入第三方的组件,问题是第三方的组件有各自的log级别,为了能接入第三方组件,mybati日志模块定义了trace、debug、warn、error级别,然后采取适配器模式将各个日志组件转化为mybatis定义的四种log级别,以此来实现日志模块的接入。Mybatis 会自动扫描日志实现,并且定义了第三方日志组件的加载顺序,加载优先级如下:slfj4-commonLoging-log4J2-log4J-JdkLog
详解自动扫描日志实现和如何实现优先级加载。
先来看一下日志实例的获取流程:框架启动的时候会调用日志模块的LogFactory.getLog()方法来获取log实例,获取到log实例后会设置到configuration对象中。LogFactory.getLog()方法其实就是拿到一个日志实现类的构造器logConstructor,并通过构造器来实例化一个实例进行返回。重点就在这个日志实现类的构造器上,构造器的类型就来源于这个日志实现类的类型。
// getLog(Class<?> aClass)方法
public static Log getLog(Class<?> aClass) {
return getLog(aClass.getName());
}
//通过类构造器实例化实例
public static Log getLog(String logger) {
try {
return logConstructor.newInstance(logger);
} catch (Throwable t) {
//如果出现异常,抛出异常,由外层处理
throw new LogException("Error creating logger for logger " + logger + ". Cause: " + t, t);
}
}
按顺序查找日志实现类:再来看一下构造器logConstructor,在LogFactory第一次初始化的时候执行static 静态代码块,按顺序查找日志实现类,找到就将实现类的构造器赋值。
public final class LogFactory {
/**
* Marker to be used by logging implementations that support markers.
*/
public static final String MARKER = "MYBATIS";
//具体日志实现类的构造器
private static Constructor<? extends Log> logConstructor;
//按顺序加载
static {
tryImplementation(LogFactory::useSlf4jLogging);
tryImplementation(LogFactory::useCommonsLogging);
tryImplementation(LogFactory::useLog4J2Logging);
tryImplementation(LogFactory::useLog4JLogging);
tryImplementation(LogFactory::useJdkLogging);
tryImplementation(LogFactory::useNoLogging);
}
1、启动一个线程去获取构造器
//启动一个线程获取日志实现类的构造器,并设置构造器的值
private static void tryImplementation(Runnable runnable) {
if (logConstructor == null) {
try {
runnable.run();
} catch (Throwable t) {
//捕捉到异常不进行处理
// ignore
}
}
}
2、查找具体实现类动作
//加载具体的日志实现
public static synchronized void useSlf4jLogging() {
setImplementation(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);
} //拿到类构造器,并给类的logConstructor变量赋值,后期getLog()方法将使用logConstructor实例一个日志类实例。
private static void setImplementation(Class<? extends Log> implClass) {
try {
Constructor<? extends Log> candidate = implClass.getConstructor(String.class);
Log log = candidate.newInstance(LogFactory.class.getName());
if (log.isDebugEnabled()) {
log.debug("Logging initialized using '" + implClass + "' adapter.");
}
//赋值
logConstructor = candidate;
} catch (Throwable t) {
throw new LogException("Error setting Log implementation. Cause: " + t, t);
}
}
最后来看一下这个日志实现类org.apache.ibatis.logging.log4j.Log4jImpl.class,其实这个日志实现类就是采用适配器模式,将log4j的日志级别,封装成mybatis的日志级
/**
* Copyright ${license.git.copyrightYears} the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.logging.slf4j; import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger; /**
* @author Clinton Begin
* @author Eduardo Macarron
*/
//实现Log 接口,通过slf4j具体实现完成适配
public class Slf4jImpl implements Log { private Log log; public Slf4jImpl(String clazz) {
Logger logger = LoggerFactory.getLogger(clazz); if (logger instanceof LocationAwareLogger) {
try {
// check for slf4j >= 1.6 method signature
logger.getClass().getMethod("log", Marker.class, String.class, int.class, String.class, Object[].class, Throwable.class);
log = new Slf4jLocationAwareLoggerImpl((LocationAwareLogger) logger);
return;
} catch (SecurityException | NoSuchMethodException e) {
// fail-back to Slf4jLoggerImpl
}
} // Logger is not LocationAwareLogger or slf4j version < 1.6
log = new Slf4jLoggerImpl(logger);
} @Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
} @Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
} @Override
public void error(String s, Throwable e) {
log.error(s, e);
} @Override
public void error(String s) {
log.error(s);
} @Override
public void debug(String s) {
log.debug(s);
} @Override
public void trace(String s) {
log.trace(s);
} @Override
public void warn(String s) {
log.warn(s);
} }
适配器模式详解
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁,将一个类的接口转换成客户希望的 另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

这里引用一个百度百科的图片
角色
Target(目标抽象类):目标抽象类定义客户所需接口,可以是一个抽象类或接口,也可以是具体类。比如:Mybatis 中的Log接口
/**
* Copyright ${license.git.copyrightYears} the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.logging; /**
* @author Clinton Begin
*/
public interface Log { boolean isDebugEnabled(); boolean isTraceEnabled(); void error(String s, Throwable e); void error(String s); void debug(String s); void trace(String s); void warn(String s); }
Adapter(适配器类):适配器可以调用另一个接口,作为一个转换器,对Adaptee和Target进行适配,适配器类是适配器模式的核心,在对象适配器中,它通过继承Target并关联一个Adaptee对象使二者产生联系。比如Mybatis中的日志模块的实现类org.apache.ibatis.logging.log4j.Log4jImpl.class
/**
* Copyright ${license.git.copyrightYears} the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.logging.log4j; import org.apache.ibatis.logging.Log;
import org.apache.log4j.Level;
import org.apache.log4j.Logger; /**
* @author Eduardo Macarron
*/
public class Log4jImpl implements Log { private static final String FQCN = Log4jImpl.class.getName(); private final Logger log; public Log4jImpl(String clazz) {
log = Logger.getLogger(clazz);
} @Override
public boolean isDebugEnabled() {
return log.isDebugEnabled();
} @Override
public boolean isTraceEnabled() {
return log.isTraceEnabled();
} @Override
public void error(String s, Throwable e) {
log.log(FQCN, Level.ERROR, s, e);
} @Override
public void error(String s) {
log.log(FQCN, Level.ERROR, s, null);
} @Override
public void debug(String s) {
log.log(FQCN, Level.DEBUG, s, null);
} @Override
public void trace(String s) {
log.log(FQCN, Level.TRACE, s, null);
} @Override
public void warn(String s) {
log.log(FQCN, Level.WARN, s, null);
} }
Adaptee(适配者类):适配者即被适配的角色,它定义了一个已经存在的接口,这个接口需要适配,适配者类一般是一个具体类,包含了客户希望使用的业务方法,在某些情况下可能没有适配者类的源代码。比如需要被使用的具体日志模块(log4j、log4j2等)
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.log4j; import org.apache.log4j.spi.LoggerFactory; /**
This is the central class in the log4j package. Most logging
operations, except configuration, are done through this class. @since log4j 1.2 @author Ceki Gülcü */
public class Logger extends Category { /**
The fully qualified name of the Logger class. See also the
getFQCN method. */
private static final String FQCN = Logger.class.getName(); protected
Logger(String name) {
super(name);
} /**
Log a message object with the {@link Level#FINE FINE} level which
is just an alias for the {@link Level#DEBUG DEBUG} level. <p>This method first checks if this category is <code>DEBUG</code>
enabled by comparing the level of this category with the {@link
Level#DEBUG DEBUG} level. If this category is
<code>DEBUG</code> enabled, then it converts the message object
(passed as parameter) to a string by invoking the appropriate
{@link org.apache.log4j.or.ObjectRenderer}. It then proceeds to call all the
registered appenders in this category and also higher in the
hierarchy depending on the value of the additivity flag. <p><b>WARNING</b> Note that passing a {@link Throwable} to this
method will print the name of the <code>Throwable</code> but no
stack trace. To print a stack trace use the {@link #debug(Object,
Throwable)} form instead. @param message the message object to log. */
//public
//void fine(Object message) {
// if(repository.isDisabled(Level.DEBUG_INT))
// return;
// if(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel())) {
// forcedLog(FQCN, Level.DEBUG, message, null);
// }
//} /**
Log a message object with the <code>FINE</code> level including
the stack trace of the {@link Throwable} <code>t</code> passed as
parameter. <p>See {@link #fine(Object)} form for more detailed information. @param message the message object to log.
@param t the exception to log, including its stack trace. */
//public
//void fine(Object message, Throwable t) {
// if(repository.isDisabled(Level.DEBUG_INT))
// return;
// if(Level.DEBUG.isGreaterOrEqual(this.getChainedLevel()))
// forcedLog(FQCN, Level.FINE, message, t);
//} /**
* Retrieve a logger named according to the value of the
* <code>name</code> parameter. If the named logger already exists,
* then the existing instance will be returned. Otherwise, a new
* instance is created.
*
* <p>By default, loggers do not have a set level but inherit it
* from their neareast ancestor with a set level. This is one of the
* central features of log4j.
*
* @param name The name of the logger to retrieve.
*/
static
public
Logger getLogger(String name) {
return LogManager.getLogger(name);
} /**
* Shorthand for <code>getLogger(clazz.getName())</code>.
*
* @param clazz The name of <code>clazz</code> will be used as the
* name of the logger to retrieve. See {@link #getLogger(String)}
* for more detailed information.
*/
static
public
Logger getLogger(Class clazz) {
return LogManager.getLogger(clazz.getName());
} /**
* Return the root logger for the current logger repository.
* <p>
* The {@link #getName Logger.getName()} method for the root logger always returns
* string value: "root". However, calling
* <code>Logger.getLogger("root")</code> does not retrieve the root
* logger but a logger just under root named "root".
* <p>
* In other words, calling this method is the only way to retrieve the
* root logger.
*/
public
static
Logger getRootLogger() {
return LogManager.getRootLogger();
} /**
Like {@link #getLogger(String)} except that the type of logger
instantiated depends on the type returned by the {@link
LoggerFactory#makeNewLoggerInstance} method of the
<code>factory</code> parameter. <p>This method is intended to be used by sub-classes. @param name The name of the logger to retrieve. @param factory A {@link LoggerFactory} implementation that will
actually create a new Instance. @since 0.8.5 */
public
static
Logger getLogger(String name, LoggerFactory factory) {
return LogManager.getLogger(name, factory);
} /**
* Log a message object with the {@link org.apache.log4j.Level#TRACE TRACE} level.
*
* @param message the message object to log.
* @see #debug(Object) for an explanation of the logic applied.
* @since 1.2.12
*/
public void trace(Object message) {
if (repository.isDisabled(Level.TRACE_INT)) {
return;
} if (Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, Level.TRACE, message, null);
}
} /**
* Log a message object with the <code>TRACE</code> level including the
* stack trace of the {@link Throwable}<code>t</code> passed as parameter.
*
* <p>
* See {@link #debug(Object)} form for more detailed information.
* </p>
*
* @param message the message object to log.
* @param t the exception to log, including its stack trace.
* @since 1.2.12
*/
public void trace(Object message, Throwable t) {
if (repository.isDisabled(Level.TRACE_INT)) {
return;
} if (Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel())) {
forcedLog(FQCN, Level.TRACE, message, t);
}
} /**
* Check whether this category is enabled for the TRACE Level.
* @since 1.2.12
*
* @return boolean - <code>true</code> if this category is enabled for level
* TRACE, <code>false</code> otherwise.
*/
public boolean isTraceEnabled() {
if (repository.isDisabled(Level.TRACE_INT)) {
return false;
} return Level.TRACE.isGreaterOrEqual(this.getEffectiveLevel());
} }
适用场景:当调用双方都不太容易修改的时候,为了复用现有组件可以使用适配器模式;在系统中接入第三方组 件的时候经常被使用到。
类图

总结:
mybatis自身没有提供实现日志实现类,而是利用了适配器模式,适配第三方日志组件,可以通过LogFactory.getLog(Class<?> aClass))获得mybaits 日志实例,并设置到configuration对象中,方便在各个需要的地方进行使用。
mybatis 架构及基础模块的更多相关文章
- SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分
SpringMVC,Spring,Hibernate,Mybatis架构开发搭建之SpringMVC部分 辞职待业青年就是有很多时间来写博客,以前在传统行业技术强度相对不大,不处理大数据,也不弄高并发 ...
- Mybatis架构学习
Mybatis架构学习 MyBatis 是支持定制化 SQL.存储过程以及高级映射的持久层框架.MyBatis 封装了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.可以对配置和原生Map使用 ...
- ASP.NET MVC +EasyUI 权限设计(三)基础模块
请注明转载地址:http://www.cnblogs.com/arhat 在上一章中呢,我们基本上搭建好了环境,那么本章我们就从基础模块开始写起.由于用户,角色,动作三个当中,都是依赖与动作的,所以本 ...
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(六)maven整合SSM
写在前面的话 承接前文<Spring+SpringMVC+MyBatis+easyUI整合基础篇(五)讲一下maven>,本篇所讲述的是如何使用maven与原ssm项目整合,使得一个普 ...
- Mybatis架构简介
一.Mybatis与ORM 对象关系映射(即Object Relational Mapping,简称ORM),主要用于关系型数据库和实体之间的映射,主要为了解决对象与关系数据库存在的互不匹配的现象,O ...
- MyBatis(十一):MyBatis架构流程浅析
架构分层 我们将MyBatis架构分为三层,分别为接口层.数据处理层和框架支撑层 接口层:提供外部接口调用的API,使用端通过这些API来操作数据库,接口层收到请求后会调用数据处理层完成具体的数据处理 ...
- python基础——模块
python基础——模块 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文 ...
- ansible中文手册-基础模块使用
此篇文章主要是翻译ansible官网文档而来,在里面讲述了如何使用ansible的基础模块,总体感觉比较晦涩,但是后面会写出自己相关实践的文档,从而更加通俗易懂,官网的东西拿来当手册偶尔翻翻也是很不错 ...
- node.js基础模块http、网页分析工具cherrio实现爬虫
node.js基础模块http.网页分析工具cherrio实现爬虫 一.前言 说是爬虫初探,其实并没有用到爬虫相关第三方类库,主要用了node.js基础模块http.网页分析工具cherri ...
随机推荐
- shellcode注入原理
我们直接写入可能无法执行 unsigned char data[130] = { 0x55, 0x8B, 0xEC, 0x83, 0xEC, 0x0C, 0xC7, 0x45, 0xF8, 0x00, ...
- 关于sqlmap当中tamper脚本编码绕过原理的一些总结(学习python没多久有些地方肯定理解有些小问题)
sqlmap中tamper脚本分析编写 置十对一些编码实现的脚本,很多sqlmap里面需要引用的无法实现,所以有一部分例如keywords就只写写了几个引用了一下,其实这里很多脚本运用是可以绕过安全狗 ...
- C语言实现顺序表的基本操作(从键盘输入 生成线性表,读txt文件生成线性表和数组生成线性表----三种写法)
经过三天的时间终于把顺序表的操作实现搞定了.(主要是在测试部分停留了太长时间) 1. 线性表顺序存储的概念:指的是在内存中用一段地址连续的存储单元依次存储线性表中的元素. 2. 采用的实现方式:一段地 ...
- django中外键的related_name属性
我先定义两个模型,一个是作者,一个是作者出版的书籍,算是一对多的类型. class Person(models.Model); name = models.CharField(verbose_name ...
- Centos-配置网络或显示当前网络接口状态-ifconfig
ifconfig 配置网络或显示当前网络接口状态,必须由root用户执行 相关选项 -a 显示所有网络接口信息,包括活动或非活动 -s 显示活动接口简要信息 -v 如果网卡接口出现错误则返回错误信息 ...
- 怎样优雅的实现INotifyPropertyChanged
第一 安装nuget包 PropertyChanged.Fody. 第二 在类的上方加上 [PropertyChanged.AddINotifyPropertyChangedInterface] 类似 ...
- LeetCode刷题总结-数学篇
本文总结LeetCode上有数学类的算法题,推荐刷题总数为40道.具体考点分析如下图: 1.基本运算问题 题号:29. 两数相除,难度中等 题号:166. 分数到小数,难度中等 题号:372. 超级次 ...
- hosts文件的内容
C:\Windows\System32\drivers\etc\hosts 1 # Copyright (c) 1993-2009 Microsoft Corp. 2 # 3 # This is a ...
- DevOps元素周期表—2号元素Kibana
Kibana 是一款开源的数据分析和可视化平台,它是 Elastic Stack 成员之一,设计用于和 Elasticsearch 协作.您可以使用 Kibana 对 Elasticsearch 索引 ...
- JavaScript筛选数组
要求: 从一个数组中,筛选出符合条件的元素,放到新数组中. 有一数组[1, 19, 2, 8, 9, 15, 11, 7, 6, 4, 18, 10],将超过10的元素删除. 代码实现: var ar ...