不再需要 Class.forName(JDBC_DRIVER)? [英] Class.forName(JDBC_DRIVER) no longer needed?
问题描述
我在这里读过,从 Java 6 开始,您不再需要使用以下方法注册 JDBC 驱动程序:
I've read here on SO that since java 6 you no longer need to register JDBC Driver using:
Class.forName(JDBC_DRIVER);
因为 DriverManager 使用位于系统属性 "jdbc.drivers" 中的路径检索正确的驱动程序.
because DriverManager uses the path located in system property "jdbc.drivers" to retrieve the correct driver.
但是当我执行以下操作时:
But when I do the followng:
System.out.print(System.getProperty("jdbc.drivers"));
null
被打印出来.
你知道我的应用程序为什么能正常工作吗?;)
Do you have any clue why my app works correctly ?? ;)
推荐答案
那与那个系统属性无关.Java6(和 JDBC4)引入了一个称为服务提供者" JVM 在启动期间可以检测到已知接口的实现.DriverManager 会自动注册符合该标准的驱动程序.这就是 Class.forName()
不再需要的原因 - 但前提是驱动程序支持.
That has nothing to do with that system property. Java6 (and JDBC4) introduced a concept known as "service provider" where implementations of known interface can be detected by the JVM during startup. A driver that is compliant with that will be registered by the DriverManager automatically. That's why Class.forName()
is no longer necessary - but only if the driver supports that.
如果在 META-INF 目录中的驱动程序 jar 文件中有 services
目录,则启动服务注册.该目录需要包含一个带有接口名称的文本文件,该接口在 JDBC 驱动程序的情况下实现,java.sql.Driver
包含实现类.
The service registration is initiated if there is a services
directory in the driver's jar file inside the META-INF directory. That directory needs to contain a text file with the name of the interface that is implemented in the case of a JDBC driver that is java.sql.Driver
containing the implementing class.
这篇关于不再需要 Class.forName(JDBC_DRIVER)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!