Class.forName("com.mysql.jdbc.Driver"); public class Driver extends NonRegisteringDriver implements java.sql.Driver { static { try { java.sql.DriverManager.registerDriver(new Driver()); //先执行DriverManager的初始化,再registerDriver方法,静态代码只走一次。 } } DriverManager类初始化: static { loadInitialDrivers(); //静态代码只走一次 }
private static void loadInitialDrivers() { String drivers; try { drivers = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return System.getProperty("jdbc.drivers"); //null } }); } AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class); //loadedDrivers = java.sql.Driver接口 Iterator<Driver> driversIterator = loadedDrivers.iterator(); try{ while(driversIterator.hasNext()) { //加载META-INF/services/java.sql.Driver,找到mysql-connector-java-5.1.45.jar!/META-INF/services/java.sql.Driver返回[com.mysql.jdbc.Driver, com.mysql.fabric.jdbc.FabricMySQLDriver] driversIterator.next(); //class com.mysql.jdbc.Driver反射出对象时候不会去执行java.sql.DriverManager.registerDriver(new Driver());因为上面已经走了一次,com.mysql.jdbc.Driver此时不在DriverManager的registeredDrivers里面, com.mysql.jdbc.Driver是在DriverManager静态代码执行完之后通过registerDriver方法加到registeredDrivers里面去的。 //com.mysql.fabric.jdbc.FabricMySQLDriver反射时候去执行java.sql.DriverManager.registerDriver(new Driver());把自己加到DriverManager的registeredDrivers里面。但是DriverManager的静态代码不会执行。因为执行过一次。 } } return null; } }); }
public class FabricMySQLDriver extends NonRegisteringDriver implements Driver { static { try { DriverManager.registerDriver(new FabricMySQLDriver()); //静态代码只走一次。 } } }