Mybatis 设计模式之装饰模式


mybatis 用装饰模式实现了Log模块。

org.apache.ibatis.logging.LogFactory 类加载的时候依次尝试使用下列Log实现

1
2
3
4
5
6
7
8
static {
tryImplementation(LogFactory::useSlf4jLogging);
tryImplementation(LogFactory::useCommonsLogging);
tryImplementation(LogFactory::useLog4J2Logging);
tryImplementation(LogFactory::useLog4JLogging);
tryImplementation(LogFactory::useJdkLogging);
tryImplementation(LogFactory::useNoLogging);
}

如果logConstructor 为空的话, 就调用setImplementation()

1
2
3
4
5
6
7
if (logConstructor == null) {
try {
runnable.run();
} catch (Throwable t) {
// ignore
}
}

在setImplementation中找到的上面的Log实现类

1
2
3
4
5
6
7
8
9
10
11
12
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);
}
}