一、背景介绍
在看spring源码和dubbo源码的时候,发现两者都用采用了JDK中spi的技术,发现都有大作用,所以就来分析下JDK中的SPI的使用方式及源码实现。
二、什么是SPI
SPI的全称是 Service Provider Interface。 一种从特定路径下,将实现了某些特定接口的类加载到内存中的方式(为什么会如此说,请看后面分析)。提供了另外一种方式加载实现类,也降低了代码的耦合程度,提升了代码的可扩展性。
实现SPI的地方主要有以下3处。主要的类和方法分别是:
- JDK
- java.util.ServiceLoader#load
- Spring
- org.springframework.core.io.support.SpringFactoriesLoader#loadFactories
- Dubbo
- org.apache.dubbo.common.extension.ExtensionLoader#
三、举例说明JDK SPI的使用方式
1. 自定义实现类, 实现数据库驱动 Driver.class
package com.fattyca1.driver; import java.sql.*; import java.util.Properties; import java.util.logging.Logger; /** * <br>自定义数据库操作</br> * * @author fattyca1 */ public abstract class CustomziedDriver implements Driver { public Connection connect(String url, Properties info) throws SQLException { return null; } public boolean acceptsURL(String url) throws SQLException { return false; } public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { return new DriverPropertyInfo[0]; } public int getMajorVersion() { return 0; } public int getMinorVersion() { return 0; } public boolean jdbcCompliant() { return false; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } // 自定义方法 protected abstract void outDbName(); }