The .forName class (JDBC_DRIVER) is no longer needed?

I read here about SO that with java 6 you no longer need to register the JDBC driver using:

Class.forName(JDBC_DRIVER); 

because DriverManager uses the path located in the "jdbc.drivers" system property to get the correct driver.

But when I do followng:

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

null is printed.

Do you have a clue why my application is working correctly ?;)

+6
source share
2 answers

This has nothing to do with this system property. Java6 (and JDBC4) introduced a concept known as a " service provider " where implementations of a well-known interface can be detected by the JVM at startup. A driver corresponding to this will be automatically registered by DriverManager. This is why Class.forName() no longer needed, but only if the driver supports this.

Service registration is initiated if the driver directory contains the services directory in the META-INF directory. This directory should contain a text file with the name of the interface, which is implemented in the case of the JDBC driver, which java.sql.Driver contains the implementation class.

+9
source

From the Javadocs DriverManager :

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

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

This means that a system property must be specified. He does not say that the class will automatically populate this property when registering the driver.

As to why your application is running, you can check that you are already calling the DriverManager#registerDriver() method (although this is not required for most drivers). If so, the driver is registered. Otherwise, the application may have a service provider file, as indicated:

The DriverManager getConnection and getDrivers have been extended to support the Java Standard Edition service provider engine. JDBC 4.0 drivers must include the META-INF/services/java.sql.Driver file. This file contains the JDBC driver name for java.sql.Driver. For example, to load my.sql.Driver class , the META-INF/services/java.sql.Driver my.sql.Driver class file would contain the entry:

+2
source

Source: https://habr.com/ru/post/981718/


All Articles