java - 理解Java自动加载Jdbc驱动的Service Provider机制

标签 java jdbc service drivers

我正在尝试准确了解 Java 的服务提供者机制如何工作以找到合适的 JDBC 驱动程序。这是我目前所拥有的:

由于 Class.ForName 不再用于显式加载 JDBC Driver ,Java 将从传递给getConnection 方法。例如,连接到 oracle 数据库的数据库 url 是这样的:

public static final String DB_URL = "jdbc:oracle:thin@//localhost:1521/ORCL";

DriverManager 然后会在项目类路径中指定的 jars 中查找 oracle 驱动程序的实现。它会在每个 jar 的 META-INF/Services 目录中查找驱动程序配置文件(其中将是实际驱动程序类的名称)。 类加载器 将加载它找到的第一个匹配项并忽略其余部分。

以上工作准确吗?如果我遗漏了什么或出了什么问题,请告诉我。

最佳答案

如果您检查源代码,您会发现 Java 不会尝试从 url 中检测驱动程序的实现名称(即驱动程序类)。相反,它会询问在类路径中找到的每个驱动程序实现是否能够处理该 url。

操作顺序似乎如下:

  • 当您请求连接时,加载 DriverManager 类。它执行一个静态 block ,加载系统属性 jdbc.drivers
  • 中指定的所有类
  • 然后调用服务提供者机制并加载它在类路径中找到的所有 java.sql.driver 类。

现在,当您请求连接时,它会循环遍历已注册的驱动程序并调用 Driver.connect(String url, Properties 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.

The driver should throw an SQLException if it is the right driver to connect to the given URL but has trouble connecting to the database.

因此第一个返回非 null 连接的驱动程序是将要使用的驱动程序。

希望对你有帮助

关于java - 理解Java自动加载Jdbc驱动的Service Provider机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26551648/

相关文章:

java - MySQL 未连接

java - 将时间字符串解析为日历时出错

java - JmsTemplate 与 IBM MQ 队列的 CachingConnectionFactory 连接恢复

java - Android:总是在 Intent 中传递的额外内容中接收空对象

android - 在 Android 2.1 后台运行的剪贴板监听器服务

java - 使用暂停和恢复选项从后台服务在 TextView 中设置运行计时器

angular - 组件中的模拟服务 - 模拟被忽略

java - 在 Java 中使用 while 循环从字符串中删除字母

java - MySQL 数据库的 ResultSet 行为,它是否将所有行存储在内存中?

java - JDBCPreparedStatement 抛出 NullPointerException