[size=large]最近在看jdbc4.0规范,想看看是如何自动获取驱动的,于是看了下DriverManager
loadInitialDrivers方法中[/size]
[size=large][url]http://stackoverflow.com/questions/4954924/getpropertyaction-vs-system-getproperty-in-obtaining-system-variables[/url]
相对于System.getProperty,GetPropertyAction更严格,当前调用的class必须被jvm信任才能从读取相关信息。至于SecurityManager这个目前还没遇到过。[/size]
[size=medium]可以看到,通过使用SPI(Service Provider Interface)查找service名称为java.sql.Driver的文件,java.sql.Driver的文件中是一个实现了该接口的类,
如:com.mysql.jdbc.Driver
然后加载这个类(具体请看sun.misc.Service),Service中LazyIterator实现了Iterator接口[/size]
loadInitialDrivers方法中[/size]
try {
drivers = (String) java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction("jdbc.drivers"));
} catch (Exception ex) {
drivers = null;
}
[size=large][url]http://stackoverflow.com/questions/4954924/getpropertyaction-vs-system-getproperty-in-obtaining-system-variables[/url]
相对于System.getProperty,GetPropertyAction更严格,当前调用的class必须被jvm信任才能从读取相关信息。至于SecurityManager这个目前还没遇到过。[/size]
DriverService ds = new DriverService();
java.security.AccessController.doPrivileged(ds);
class DriverService implements java.security.PrivilegedAction {
Iterator ps = null;
public DriverService() {};
public Object run() {
// uncomment the followin line before mustang integration
// Service s = Service.lookup(java.sql.Driver.class);
// ps = s.iterator();
ps = Service.providers(java.sql.Driver.class);
/* Load these drivers, so that they can be instantiated.
* It may be the case that the driver class may not be there
* i.e. there may be a packaged driver with the service class
* as implementation of java.sql.Driver but the actual class
* may be missing. In that case a sun.misc.ServiceConfigurationError
* will be thrown at runtime by the VM trying to locate
* and load the service.
*
* Adding a try catch block to catch those runtime errors
* if driver not available in classpath but it's
* packaged as service and that service is there in classpath.
*/
try {
while (ps.hasNext()) {
ps.next();
} // end while
} catch(Throwable t) {
// Do nothing
}
return null;
} //end run
} //end DriverService
[size=medium]可以看到,通过使用SPI(Service Provider Interface)查找service名称为java.sql.Driver的文件,java.sql.Driver的文件中是一个实现了该接口的类,
如:com.mysql.jdbc.Driver
然后加载这个类(具体请看sun.misc.Service),Service中LazyIterator实现了Iterator接口[/size]