[JVM] study notes ServiceLoader class

Maven a new project, the introduction mysql dependencies, and then run the following code

public class Test {
    public static void main(String[] args) {
        ServiceLoader<Driver> loader = ServiceLoader.load(Driver.class);
        Iterator<Driver> iterator = loader.iterator();
        while (iterator.hasNext()) {
            Driver driver = iterator.next();
            System.out.println("driver: "+driver.getClass()+", loader: "+driver.getClass().getClassLoader());
        }

        System.out.println("当前线程上下文类加载器: "+Thread.currentThread().getContextClassLoader());
        System.out.println("ServiceLoader的累加载器: "+ServiceLoader.class.getClassLoader());
    }
}

operation result

Driver: class sun.jdbc.odbc.JdbcOdbcDriver, Loader: null 
Driver: class com.mysql.jdbc.Driver, Loader: sun.misc.Launcher$AppClassLoader@1c898b41 
current thread context class loader: sun.misc.Launcher $ AppClassLoader 1c898b41 @ 
ServiceLoader tired loader: null

ServiceLoader code and Driver are comes with the JDK class, why ServiceLoader <Driver> loader = ServiceLoader.load (Driver.class); MySql able to load a driver do?

This is actually a SPI specification, there are specific instructions in the doc document ServiceLoader class in order to load the mysql driver, is really specification requires third-party implementations must file META-INF / Service jar caught in the path of the package below, the contents of a text file named java.sql.Driver, the file name is the name of the server interface, indicating that the jar contains plenty achieve this type of service, the contents of a text file is com.mysql.jdbc.Driver, shows that the implementation class the fully qualified name.

Guess you like

Origin www.cnblogs.com/heben/p/11456580.html