一、在未主动设置上下文类加载器时,线程上下文类加载器为应用类加载器(AppClassLoader)
1.引入MySQL包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
2.测试ThreadContextClassLoader
package cn.edu.tju;
import java.sql.Driver;
import java.util.Iterator;
import java.util.ServiceLoader;
public class ThreadContextClassLoaderTest {
public static void main(String[] args) {
ServiceLoader<Driver> serviceLoader=ServiceLoader.load(Driver.class);
Iterator<Driver> iterator = serviceLoader.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().getClass());
}
}
}
3.运行输出:
4.结果分析:因为没有设置ThreadContexClassLoader,所以主线程的ThreadContextClassLoader为AppClassLoader,其能够从应用的类路径加载MySQL的两个Driver类。
5.修改主类:
package cn.edu.tju;
import java.sql.Driver;
import java.util.Iterator;
import java.util.ServiceLoader;
public class ThreadContextClassLoaderTest {
public static void main(String[] args) {
Thread.currentThread().setContextClassLoader(SpiTest.class.getClassLoader().getParent());
ServiceLoader<Driver> serviceLoader=ServiceLoader.load(Driver.class);
Iterator<Driver> iterator = serviceLoader.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().getClass());
}
}
}
将线程的上下文类加载器改为了AppClassLoader的parent即ExtClassLoader,将无法加载类路径下的MySQL的Driver类,因此,程序运行没有输出