以下内容来自:http://blog.csdn.net/mosquitolxw/article/details/25290315
What is the difference between Service Provider Interface (SPI) and Application Programming Interface (API)?
More specifically, for Java libraries, what makes them an API and/or SPI?
the API is the description of classes/interfaces/methods/... that you call and use to achieve a goal
the SPI is the description of classes/interfaces/methods/... that you extend and implement to achieve a goal
Put differently, the API tells you what a specific class/method does for you and the SPI tells you what you must do to conform.
Sometimes SPI and API overlap. For example in JDBC the Driver class is part of the SPI: If you simply want to use JDBC, you don't need to use it directly, but everyone who implements a JDBC driver must implement that class.
The Connection interface on the other hand is both SPI and API: You use it routinely when you use a JDBC driver and it needs to be implemented by the developer of the JDBC driver.
以下内容来自:http://www.cnblogs.com/happyframework/p/3349087.html
背景
Java 中区分 Api 和 Spi,通俗的讲:Api 和 Spi 都是相对的概念,他们的差别只在语义上,Api 直接被应用开发人员使用,Spi 被框架扩张人员使用。
Java类库中的实例
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "123456");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from Users");
说明:java.sql.Driver 是 Spi,com.mysql.jdbc.Driver 是 Spi 实现,其它的都是 Api。
如何实现这种结构?
public class Program {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
Class.forName("SpiA");
Api api = new Api("a");
api.Send("ABC");
}
}
import java.util.*;
public class Api {
private static HashMap<String, Class<? extends Spi>> spis =
new HashMap<String, Class<? extends Spi>>();
private String protocol;
public Api(String protocol) {
this.protocol = protocol;
}
public void Send(String msg) throws InstantiationException,
IllegalAccessException {
Spi spi = spis.get(protocol).newInstance();
spi.send("消息发送开始");
spi.send(msg);
spi.send("消息发送结束");
}
public static void Register(String protocol, Class<? extends Spi> cls) {
spis.put(protocol, cls);
}
}
public interface Spi {
void send(String msg);
}
public class SpiA implements Spi {
static {
Api.Register("a", SpiA.class);
}
@Override
public void send(String msg) {
System.out.println("SpiA:" + msg);
}
}
说明:Spi 实现的加载可以使用很多种方式,文中是最基本的方式。