SPI:Service Provider Interface是JDK内置的服务发现机制。
是一种将服务接口与服务实现分离以达到解耦、大大提升了程序可扩展性的机制。
SPI使用规范
- 在classpath目录下创建 META-INF/services 目录。
- 创建以接口全限定名命名的文件。
- 在文件中编写实现类的全限定名。
- 多个实现类用换行符分隔。
- 使用ServiceLoader加载服务。
例子
Person接口
public interface Person {
void say();
}
PersonImpl实现类
public class PersonImpl implements Person {
@Override
public void say() {
System.out.println("say hello");
}
}
Client测试
public class Client {
public static void main(String[] args) {
//通过ServiceLoader 去加载实现类
ServiceLoader<Person> load = ServiceLoader.load(Person.class);
for (Person person : load) {
String name = person.getClass().getName();
System.out.println(name);
person.say();
}
}
}
输出:
com.ch.test.PersonImpl
say hello
在Client中,我们并没有new实现类,通过将实现类配置在配置文件中,由JDK的ServiceLoader去自动加载实现类。
其他例子
MySQL就是一个很好的例子。
老版本的mysql-connector中,我们需要手动加载驱动。
Class.forName("com.mysql.jdbc.Driver");
新版本中,可以直接获取连接了。
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
String catalog = connection.getCatalog();
connection.close();
System.out.println(catalog);
输出:
test
通过查看mysql-connector的jar包可以发现有这么一个文件:
META-INF/services/java.sql.Driver
文件内容为:
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver