描述
JAVA的SPI机制是一种扩展实现,在JDBC中有体现。java中提供数据库操作的接口也就是规范,各数据库厂商提供具体的实现类,也就是驱动。比如mysql的连接驱动会在其jar包的META-INF/service中提供一个文件名为实现的接口名,内容为具体的实现类的全路径。当jar包导入进来之后,DriverManager会自动利用反射实例化。
示例
@Test
public void testConnection5() {
try {
InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String url=properties.getProperty("url");
String user=properties.getProperty("user");
String password=properties.getProperty("password");
/**
* 此处注释掉也可以正常运行
* 因为:用到了java的spi机制,导入的jar包中META-INF/service下
* 存在接口java.sql.Driver的全路径com.mysql.cj.jdbc.Driver
* 采用spi机制,接口的发现机制,所以会自动调用此实现类的实例化
*/
// String classsName="com.mysql.jdbc.Driver";
// Class.forName(classsName);
// Class clazz= Class.forName(classsName);
// Driver driver = (Driver) clazz.newInstance();
//
// DriverManager.registerDriver(driver);
Connection connect = DriverManager.getConnection(url, user, password);
System.out.println(connect);
} catch (Exception e) {
e.printStackTrace();
}
SPI机制代码
@Test
public void test() throws Exception {
InputStream is = ClassLoader.getSystemResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
ServiceLoader<Driver> load = ServiceLoader.load(Driver.class);
Iterator<Driver> iterator = load.iterator();
while (iterator.hasNext()){
Driver driver = iterator.next();
if (driver instanceof com.mysql.jdbc.Driver){
Connection connect = driver.connect(properties.getProperty("url"),properties);
System.out.println(connect);
}
}
}
结果:com.mysql.jdbc.JDBC4Connection@4563e9ab