Java執行緒上下文類載入器與SPI
我們拿jdbc為例子分析:
檢視DriverManager原始碼
其中ServiceLoader.load(Driver.class)方法原始碼:private DriverManager(){} /** * Load the initial JDBC drivers by checking the System property * jdbc.properties and then use the {@code ServiceLoader} mechanism */ static { loadInitialDrivers(); println("JDBC DriverManager initialized"); } private static void loadInitialDrivers() { AccessController.doPrivileged(new PrivilegedAction<Void>() { //省略... public Void run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); Iterator driversIterator = loadedDrivers.iterator(); //省略... return null; } }); } }
public static <S> ServiceLoader<S> load(Class<S> service) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return ServiceLoader.load(service, cl);
}
可見jdbc在通過SPI方式載入service實現類的時候是使用的執行緒上下文載入器載入的。