Class.forName(JDBC_DRIVER) 不再需要?

Class.forName(JDBC_DRIVER) no longer needed?

我在这里读到,自 java 6 起,您不再需要使用以下方式注册 JDBC 驱动程序:

Class.forName(JDBC_DRIVER);

因为DriverManager使用了系统中的路径属性 "jdbc.drivers" 检索正确的驱动程序。

但是当我执行以下操作时:

System.out.print(System.getProperty("jdbc.drivers"));

null 得到打印。

你知道我的应用程序为什么能正常运行吗?? ;)

这与那个系统无关属性。 Java6(和 JDBC4)引入了一个称为“service provider”的概念,其中 JVM 在启动期间可以检测到已知接口的实现。符合该要求的驱动程序将由 DriverManager 自动注册。这就是为什么不再需要 Class.forName() - 但前提是驱动程序支持它。

如果META-INF目录下的驱动jar文件中有services目录,则启动服务注册。该目录需要包含一个文本文件,其中包含在 JDBC 驱动程序 java.sql.Driver 包含实现 class.

的情况下实现的接口名称

来自 DriverManager 的 Java 文档:

As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications. For example in your ~/.hotjava/properties file you might specify:

jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver

这意味着不需要指定系统 属性(因为它说 DriverManager 尝试 )。还有另一种自动加载驱动程序的机制,它依赖于 service loading since Java 6:

The DriverManager methods getConnection and getDrivers have been enhanced to support the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers must include the file META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Driver.

现在几乎所有 JDBC 驱动程序都符合此要求。请注意,DriverManager 不会在内部填充 jdbc.drivers 属性,因此它仍然为空。