As for JDBC4 it is required that the JDBC driver loads automatically. It is made by adding a static block where the driver registers in DriverManager. However when I’m writing such a block in my class, it is executed only when I create the object of this class. Otherwise the code is not run.
My question is: how do the drivers initilize itself, when they are not being created from the application code, however they are registered in DriverManager when I use it for getting db connection?
You can use the
ServiceLoaderfacility of Java to automatically load services.You need to put a file in the JAR that lists your class, then Java will automatically load it when the service is needed. Check the documentation for ServiceLoader for more details.
The answer to this similar question actually says that this is the way that JDBC uses.