JAVA(3)- 线程上下文类加载器
前言
线程上下文类加载器扩展:
概念
SPI:Service Provider Interface 、由JDK定义的一套标准接口,方便扩展各个厂商的不同实现
1、为什么需要线程上下文类加载器
- JDK核心库中提供了很多SPI(Service Provider Interface),常见的SPI包括JDBC、JCE、JNDI、JAXP、和JBI等、JDK只规定了这些接口之间的逻辑关系,但不提供具体的实现,具体的实现由第三方厂商提供,这样做的好处是JDBC提供了高度抽象,应用程序只需要面向接口编程。
- 问题:java.lang.sql中的所有接口都由JDK提供、加载这些类的是根类加载器,第三方提供的是系统应用类加载器,由于JVM的双亲委托机制,比如Connections、Statement、RowSet等都是由根类加载器加载、第三方的类不会被加载,那是如何解决这个问题的呢?
2、数据库驱动初始化源码分析
- rt.jar包 DriverManager 是BootstrapClassLoader加载
- 父类加载器委托子类类加载器去加载 破坏双亲委派模型
callerCL = Thread.currentThread().getContextClassLoader();
aClass = Class.forName(driver.getClass().getName(), true, classLoader);
// Worker method called by the public getConnection() methods.
private static Connection getConnection(
String url, java.util.Properties info, Class<?> caller) throws SQLException {
/*
* When callerCl is null, we should check the application's
* (which is invoking this class indirectly)
* classloader, so that the JDBC driver class outside rt.jar
* can be loaded from here.
*/
ClassLoader callerCL = caller != null ? caller.ge