JDK有个ServiceLoader类,在java.util包里,支持按约定目录/META-INF/services去找到接口全路径命名的文件,读取文件内容得到接口实现类的全路径,加载并实例化。如果我们在自己的代码中定义一个接口,别人按接口实现并打包好了,那么我们只需要引入jar包,通过ServiceLoader就能够把别人的实现用起来。举个例子,JDK中的JDBC提供一个数据库连接驱动接口,不同的厂商可以有不同的实现,如果它们给的jar包里按规定提供了配置和实现类,那么我们就可以执行不同的数据库连接操作,比如MySql的jar包里就会有自己的配置:
这里文件名就是接口:
文件内容是实现类:
以上就是java的SPI(Service Provider Interface)机制,支持第三方扩展我们的接口实现。我们自己实现一个简单例子,为了省去打jar包的麻烦,把目录放到maven项目结构中的resources下即可,这里就是classpath,跟你放jar包里效果一样。
1、定义一个接口:
packagecom.wlf.service;public interfaceITest {voidsaySomething();
}
2、定义两个实现:
packagecom.wlf.service.impl;importcom.wlf.service.ITest;public class ITestImpl1 implementsITest {
@Overridepublic voidsaySomething() {
System.out.println("Hi, mia.");
}
}
packagecom.wlf.service.impl;importcom.wlf.service.ITest;public class ITestImpl2 implementsITest {
@Overridepublic voidsaySomething() {
System.out.println("Hello, world.");
}
}
3、按预定新增/META-INF/services/com.wlf.service.ITest文件:
com.wlf.service.impl.ITestImpl1
com.wlf.service.impl.ITestImpl2
4、定义一个执行类,通过ServiceLoader加载并实例化,调用实现类方法,跑一下:
packagecom.wlf.service;importjava.util.Iterator;importjava.util.ServiceLoader;public classTestServiceLoader {public static voidmain(String[] args) {
ServiceLoader serviceLoader = ServiceLoader.load(ITest.class);
Iterator iTests =serviceLoader.iterator();while(iTests.hasNext()) {
ITest iTest=iTests.next();
System.out.printf("loading %s\n", iTest.getClass().getName());
iTest.saySomething();
}
}
}
打印结果:
ServiceLoader源码比较简单,可以看下上面我们使用到的标黄了的方法:
/*** Lazily loads the available providers of this loader's service.
*
*
The iterator returned by this method first yields all of the
* elements of the provider cache, in instantiation order. It then lazily
* loads and instantiates any remaining providers, adding each one to the
* cache in turn.
*
*
To achieve laziness the actual work of parsing the available
* provider-configuration files and instantiating providers must be done by
* the iterator itself. Its {@linkjava.util.Iterator#hasNext hasNext} and
* {@linkjava.util.Iterator#next next} methods can therefore throw a
* {@linkServiceConfigurationError} if a provider-configuration file
* violates the specified format, or if it names a provider class that
* cannot be found and instantiated, or if the result of instantiating the
* class is not assignable to the service type, or if any other kind of
* exception or error is thrown as the next provider is located and
* instantiated. To write robust code it is only necessary to catch {@link* ServiceConfigurationError} when using a service iterator.
*
*
If such an error is thrown then subsequent invocations of the
* iterator will make a best effort to locate and instantiate the next
* available provider, but in general such recovery cannot be guaranteed.
*
*
* style="padding-right: 1em; font-weight: bold">Design Note
* Throwing an error in these cases may seem extreme. The rationale for
* this behavior is that a malformed provider-configuration file, like a
* malformed class file, indicates a serious problem with the way the Java
* virtual machine is configured or is being used. As such it is
* preferable to throw an error rather than try to recover or, even worse,
* fail silently.
*
*
The iterator returned by this method does not support removal.
* Invoking its {@linkjava.util.Iterator#remove() remove} method will
* cause an {@linkUnsupportedOperationException} to be thrown.
*
* @implNote When adding providers to the cache, the {@link#iterator
* Iterator} processes resources in the order that the {@link* java.lang.ClassLoader#getResources(java.lang.String)
* ClassLoader.getResources(String)} method finds the service configuration
* files.
*
*@returnAn iterator that lazily loads providers for this loader's
* service*/
public Iteratoriterator() {return new Iterator() {
Iterator>knownProviders=providers.entrySet().iterator();public booleanhasNext() {if(knownProviders.hasNext())return true;returnlookupIterator.hasNext();
}publicS next() {if(knownProviders.hasNext())returnknownProviders.next().getValue();returnlookupIterator.next();
}public voidremove() {throw newUnsupportedOperationException();
}
};
}
我们用到的迭代器其实是一个Map:
//Cached providers, in instantiation order
private LinkedHashMap providers = new LinkedHashMap<>();
它用来缓存加载的实现类,真正执行的是lookupIterator:
//The current lazy-lookup iterator
private LazyIterator lookupIterator;
我们看下它的hasNext和next方法:
public booleanhasNext() {if (acc == null) {returnhasNextService();
}else{
PrivilegedAction action = new PrivilegedAction() {public Boolean run() { returnhasNextService(); }
};returnAccessController.doPrivileged(action, acc);
}
}publicS next() {if (acc == null) {returnnextService();
}else{
PrivilegedAction action = new PrivilegedAction() {public S run() { returnnextService(); }
};returnAccessController.doPrivileged(action, acc);
}
}
private booleanhasNextService() {if (nextName != null) {return true;
}if (configs == null) {try{
String fullName= PREFIX +service.getName();if (loader == null)
configs=ClassLoader.getSystemResources(fullName);elseconfigs=loader.getResources(fullName);
}catch(IOException x) {
fail(service,"Error locating configuration files", x);
}
}while ((pending == null) || !pending.hasNext()) {if (!configs.hasMoreElements()) {return false;
}
pending=parse(service, configs.nextElement());
}
nextName=pending.next();return true;
}privateS nextService() {if (!hasNextService())throw newNoSuchElementException();
String cn=nextName;
nextName= null;
Class> c = null;try{
c= Class.forName(cn, false, loader);
}catch(ClassNotFoundException x) {
fail(service,"Provider " + cn + " not found");
}if (!service.isAssignableFrom(c)) {
fail(service,"Provider " + cn + " not a subtype");
}try{
S p=service.cast(c.newInstance());
providers.put(cn, p);returnp;
}catch(Throwable x) {
fail(service,"Provider " + cn + " could not be instantiated",
x);
}throw new Error(); //This cannot happen
}public booleanhasNext() {if (acc == null) {returnhasNextService();
}else{
PrivilegedAction action = new PrivilegedAction() {public Boolean run() { returnhasNextService(); }
};returnAccessController.doPrivileged(action, acc);
}
}
hasNext查找实现类,并指定了类路径:
private static final String PREFIX = "META-INF/services/";
具体查找操作看这里:
pending = parse(service, configs.nextElement());
next则是实例化加载到的实现类,使用反射Class.forName加载类、newInstance实例化对象。通过jar包引入接口和实现的例子参见Java的SPI引入Jar包简单例子。