Class.forName("com.mysql.jdbc.Driver") 什么作用

 我们知道当我们连接MySQL数据库时,会使用如下代码:

1 try {
2        Class.forName("com.mysql.jdbc.Driver");
3        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
4 } catch (Exception e) {
5        e.printStackTrace();
6 }

  那么Class.forName()有什么作用呢?

  首先我们知道Class.forName() 方法要求JVM查找并加载指定的类到内存中,此时将"com.mysql.jdbc.Driver" 当做参数传入,就是告诉JVM,去"com.mysql.jdbc"这个路径下找Driver类,将其加载到内存中。

由于加载类文件时会执行其中的静态代码块,其中Driver类的源码如下

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
    public Driver() throws SQLException {
    }

    static {
        try {
            DriverManager.registerDriver(new Driver());//首先new一个Driver对象,并将它注册到DriverManage中
        } catch (SQLException var1) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

 接下来我们再看看这个DriverManager.registerDriver 方法:

    public static synchronized void registerDriver(java.sql.Driver driver)
        throws SQLException {

        registerDriver(driver, null);
    }

 继续看这个registerDriver(driver, null) 方法

private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();// registeredDrivers 是一个支持并发的arraylist
......
public static void registerDriver(java.sql.Driver driver, DriverAction da)
        throws SQLException {
        if (driver != null) {
            //如果该驱动尚未注册,那么将他添加到 registeredDrivers 中去。这是一个支持并发情况的特殊ArrayList
            registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }
        println("registerDriver: " + driver);
    }

此时,Class.forName(“com.mysql.jdbc.Driver”) 的工作就完成了,工作就是:将mysql驱动注册到DriverManager中去。接下来我们看是怎么进行调用的

2、DriverManager.getConnection方法分析

注册到DriverManager中之后,我们就可以通过DriverManager的getConnection方法获得mysql的连接了:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");

接下来我们在看看这个getConnection方法:

@CallerSensitive
public static Connection getConnection(String url,
    String user, String password) throws SQLException {
    ....
    return (getConnection(url, info, Reflection.getCallerClass()));
}

同样,调用了自身的 getConnection方法,继续往下看

 1 private static Connection getConnection(
 2         String url, java.util.Properties info, Class<?> caller) throws SQLException {
 3         ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;
 4         synchronized(DriverManager.class) {
 5             // synchronize loading of the correct classloader.
 6             if (callerCL == null) {
 7                 callerCL = Thread.currentThread().getContextClassLoader();
 8             }
 9         }
10         // Walk through the loaded registeredDrivers attempting to make a connection.
11         // Remember the first exception that gets raised so we can reraise it.
12         SQLException reason = null;
13 
14         for(DriverInfo aDriver : registeredDrivers) {
15             // If the caller does not have permission to load the driver then skip it.
16             if(isDriverAllowed(aDriver.driver, callerCL)) {
17                 try {
18                     Connection con = aDriver.driver.connect(url, info);
19                     if (con != null) {
20                         // Success!
21                         return (con);
22                     }
23                 } catch (SQLException ex) {
24                     if (reason == null) {
25                         reason = ex;
26                     }
27                 }
28             } else {
29                 println("skipping: " + aDriver.getClass().getName());
30             }
31         }
32 
33         // if we got here nobody could connect.
34         if (reason != null)    {
35             println("getConnection failed: " + reason);
36             throw reason;
37         }
38         throw new SQLException("No suitable driver found for "+ url, "08001");
39     }

可以看到它对上文提到的静态变量 registeredDrivers 进行了遍历,调用了connect(url, info)方法,这是一个接口,由各个不同的驱动自己实现。

    /**
     * Attempts to make a database connection to the given URL.
     * The driver should return "null" if it realizes it is the wrong kind
     * of driver to connect to the given URL.  This will be common, as when
     * the JDBC driver manager is asked to connect to a given URL it passes
     * the URL to each loaded driver in turn.
     */
    Connection connect(String url, java.util.Properties info)
        throws SQLException;

到此为止,我们就获得了connection对象,现在就可以对数据库进行操作了。

3、不手动注册驱动也能使用JDBC [ 去除class.forName ]

高版本的Oracle、MySql已经不需要写class.forName了,在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");
    }

进入loadInitialDrivers()方法中看到以下一段代码:

 1 private static void loadInitialDrivers() {
 2         String drivers;
 3         try {
 4             drivers = AccessController.doPrivileged(new PrivilegedAction<String>() {
 5                 public String run() {
 6                     return System.getProperty("jdbc.drivers");
 7                 }
 8             });
 9         } catch (Exception ex) {
10             drivers = null;
11         }
12         // If the driver is packaged as a Service Provider, load it.
13         // Get all the drivers through the classloader
14         // exposed as a java.sql.Driver.class service.
15         // ServiceLoader.load() replaces the sun.misc.Providers()
16 
17         AccessController.doPrivileged(new PrivilegedAction<Void>() {
18             public Void run() {
19 
20                 ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
21                 Iterator<Driver> driversIterator = loadedDrivers.iterator();
22 
23                 /* Load these drivers, so that they can be instantiated.
24                  * It may be the case that the driver class may not be there
25                  * i.e. there may be a packaged driver with the service class
26                  * as implementation of java.sql.Driver but the actual class
27                  * may be missing. In that case a java.util.ServiceConfigurationError
28                  * will be thrown at runtime by the VM trying to locate
29                  * and load the service.
30                  *
31                  * Adding a try catch block to catch those runtime errors
32                  * if driver not available in classpath but it's
33                  * packaged as service and that service is there in classpath.
34                  */
35                 try{
36                     while(driversIterator.hasNext()) {
37                         driversIterator.next();
38                     }
39                 } catch(Throwable t) {
40                 // Do nothing
41                 }
42                 return null;
43             }
44         });

重点是第20行,ServiceLoader.load(Driver.class)

上面这行代码可以把类路径下所有jar包中META-INF/services/java.sql.Driver文件中定义的类加载上来,此类必须继承自java.sql.Driver。

Class.forName的主要目的是初始化数据库驱动,以执行驱动的静态块代码,其实主要是DriverManager.registerDriver(driver)方法。自己驱动包的驱动名当然开发商最清楚,所以就在发布驱动包的时候就直接配置了,所以不用再写Class.forName。
 

转载链接: https://blog.csdn.net/zt928815211/article/details/83420828

  https://www.zhihu.com/question/22925738/answer/23088255

猜你喜欢

转载自www.cnblogs.com/qingchen521/p/10331768.html
今日推荐