问题
I am trying to get an accurate understanding of how Java's Service Provider Mechanism works to locate the appropriate JDBC driver. Here is what I have so far:
Since Class.ForName
is no longer used to explicitly load a JDBC Driver
, Java would know what type driver it needs from the database url string that one passes to the getConnection
method. For instance the database url to connect to a oracle database would be something like this:
public static final String DB_URL = "jdbc:oracle:thin@//localhost:1521/ORCL";
The DriverManager
would then look for implementation of oracle driver in the jars specified in the projects class path. It would look for the drivers configuration files (in which would be the name of actual driver classes) in META-INF/Services
directory of each jar. The Class Loader
will load the very first match that it finds and ignore the rest.
Is the above working accurate ? Please let me know If I missed something or got something wrong.
回答1:
If you check the source code you will see that Java does not try to detect the driver's implementation name (i.e. the driver class) from the url. Instead it asks each driver implementation it finds in the classpath if they are able to handle that url or not.
The order of actions seems to be the following:
- When you ask for the connection the
DriverManager
class is loaded. It executes a static block that loads all the classes specified in the system propertyjdbc.drivers
- Then the Service Provider Mechanism is invoked and loads all classes of
java.sql.driver
it finds in the classpath.
Now when you ask it for a connection it loops through the registered drivers and call the Driver.connect(String url, Properties info) method on them. Quote:
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.
So the first driver that returns a non null
connection is the driver that will be used.
Hope that helps
来源:https://stackoverflow.com/questions/26551648/understanding-javas-service-provider-mechanism-that-automatically-loads-the-jdb