SPI是Service Provider Interface的缩写,能够使用它扩展框架和更换的组件。JDK提供了java.util.ServiceLoader工具类,在使用某个服务接口时,它能够帮助咱们查找该服务接口的实现类,加载和初始化,前提条件是基于它的约定。java
大多数开发人员可能不熟悉,却常用它。举个例子,获取MySQL数据库链接,代码以下:mysql
public class MySQLConnect {
private final static String url ="jdbc:mysql://localhost:3306/test";
private final static String username = "root";
private final static String password = "root";
public static Connection getConnection() throws SQLException {
// Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url,username,password);
}
public static void main(String[] args) throws SQLException {
System.out.println(getConnection());
}
}
复制代码
上述代码是能够运行成功的。接下来咱们就分析下DriverManager.getConnection(url,username,password)的过程,探究其如何获取到数据库链接Connection?sql
一、首先分析loadInitialDrivers方法,其源码以下:数据库
private static void loadInitialDrivers() {
/** * 获取ServiceLoader实例,loadedDrivers = * new ServiceLoader(Driver.class,Thread.currentThread().getContextClassLoader()) */
ServiceLoader<Driver> loadedDrivers = ServiceLoader.load(Driver.class);
/** * 获取serviceLoader实例的迭代器,driversIterator = new LazyIterator(service, loader) */
Iterator<Driver> driversIterator = loadedDrivers.iterator();
/** * 应用程序加载器(Thread.currentThread().getContextClassLoader()) * 加载classpath下META-INF/services/java.sql.Driver文件, * 解析java.sql.Driver文件的内容将其存储在LazyIterator.pending实例变量中。 */
while(driversIterator.hasNext()) {
/** * 经过反射实例化java.sql.Driver文件中的类(com.mysql.jdbc.Driver, com.mysql.fabric.jdbc.FabricMySQLDriver) */
driversIterator.next();
}
}
复制代码
约定:当服务的提供者,提供了服务接口(java.sql.Driver)的一种实现以后,在jar包的META-INF/services/目录里同时建立一个以服务接口命名的文件。该文件里就是实现该服务接口的具体实现类。而当外部程序装配这个模块的时候,就能经过该jar包META-INF/services/里的配置文件找到具体的实现类名,并装载实例化,完成模块的注入。微信
二、com.mysql.jdbc.Driver类的初始化 框架
static {
try {
// registeredDrivers存储Dirver实例
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
复制代码
三、获取数据库链接ide
for(DriverInfo aDriver : registeredDrivers) {
if(isDriverAllowed(aDriver.driver, callerCL)) {
try {
// 获取Connection
Connection con = aDriver.driver.connect(url, info);
if (con != null) {
return (con);
}
} catch (SQLException ex) {
if (reason == null) {
reason = ex;
}
}
} else {
println("skipping: " + aDriver.getClass().getName());
}
}
复制代码
一、目录结构工具
二、示例代码测试
public interface HelloService {
String sayHello();
}
public class CHelloService implements HelloService {
@Override
public String sayHello() {
return "Welcome to C world";
}
}
public class JavaHelloService implements HelloService {
@Override
public String sayHello() {
return "Welcome to Java world";
}
}
复制代码
三、com.codersm.study.jdk.spi.HelloService文件内容url
com.codersm.study.jdk.spi.impl.CHelloService
com.codersm.study.jdk.spi.impl.JavaHelloService
复制代码
四、测试
@Test
public void testSpi() {
ServiceLoader<HelloService> loaders = ServiceLoader.load(HelloService.class);
for (HelloService loader : loaders) {
System.out.println(loader.sayHello());
}
}
复制代码
欢迎留言补充,共同交流。我的微信公众号求关注: