DriverManager

[size=large]最近在看jdbc4.0规范,想看看是如何自动获取驱动的,于是看了下DriverManager
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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值