Java SPI机制

来源:互联网 发布:梦幻西游mac右键 编辑:程序博客网 时间:2024/05/22 02:32
有这样的一个应用场景,在某个JAR包内,有一个接口IA,然后有3个IA接口的具体实现类,分别是AIA,BIA,CIA。

那么如果在该JAR包内其他的类中使用接口IA的时候,硬编码IA对象对应的具体实现类,就会导致非常不灵活。这就是SPI机制产生的场景由来。


一、SPI机制概念
SPI的全称是Service Provider Interface。

简单来说,SPI机制提供了一个表达接口和其具体实现类之间的绑定关系的方案。具体是在JAR包的"META-INF/services/"目录下建立一个文件,文件名是接口的全限定名,文件的内容可以有多行,每行都是该接口对应的具体实现类的全限定名。


二、使用例子
2.1、 commons-logging中的例子

在commons-logging:commons-logging:1.1包中有个LogFactory抽象类(全限定名是"org.apache.commons.logging.LogFactory"),在其中有个静态方法

public static LogFactory getFactory() throws LogConfigurationException

用于获取一个默认的LogFactory实例。


在该方法中,有一段Java代码片段如下:
[java] view plain copy
  1. if(factory == null) {  
  2.                 if(isDiagnosticsEnabled()) {  
  3.                     logDiagnostic("[LOOKUP] Looking for a resource file of name [META-INF/services/org.apache.commons.logging.LogFactory] to define the LogFactory subclass to use...");  
  4.                 }  
  5.   
  6.   
  7.                 try {  
  8.                     InputStream names1 = getResourceAsStream(contextClassLoader, "META-INF/services/org.apache.commons.logging.LogFactory");  
  9.                     if(names1 != null) {  
  10.                         BufferedReader name;  
  11.                         try {  
  12.                             name = new BufferedReader(new InputStreamReader(names1, "UTF-8"));  
  13.                         } catch (UnsupportedEncodingException var7) {  
  14.                             name = new BufferedReader(new InputStreamReader(names1));  
  15.                         }  
  16.   
  17.   
  18.                         value = name.readLine();  
  19.                         name.close();  
  20.                         if(value != null && !"".equals(value)) {  
  21.                             if(isDiagnosticsEnabled()) {  
  22.                                 logDiagnostic("[LOOKUP]  Creating an instance of LogFactory class " + value + " as specified by file \'" + "META-INF/services/org.apache.commons.logging.LogFactory" + "\' which was present in the path of the context" + " classloader.");  
  23.                             }  
  24.   
  25.   
  26.                             factory = newFactory(value, baseClassLoader, contextClassLoader);  
  27.                         }  
  28.                     } else if(isDiagnosticsEnabled()) {  
  29.                         logDiagnostic("[LOOKUP] No resource file with name \'META-INF/services/org.apache.commons.logging.LogFactory\' found.");  
  30.                     }  
  31.                 } catch (Exception var8) {  
  32.                     if(isDiagnosticsEnabled()) {  
  33.                         logDiagnostic("[LOOKUP] A security exception occurred while trying to create an instance of the custom factory class: [" + var8.getMessage().trim() + "]. Trying alternative implementations...");  
  34.                     }  
  35.                 }  
  36. }  


这段代码的意思就是说使用SPI机制,在Jar包的"META-INF/services/"目录下查找一个文件名为"org.apache.commons.logging.LogFactory"的文件,在文件中可以配置默认要使用的LogFactory具体实现类的全限定名。


2.2、自己的例子

现在有以下类层次结构


IA的内容如下:

[java] view plain copy
  1. package spi;  
  2.   
  3. public interface IA {  
  4.     void doIt();  
  5. }  

AIA的内容如下:

[java] view plain copy
  1. package spi;  
  2.   
  3. public class AIA implements IA {  
  4.     public void doIt() {  
  5.         System.out.println("doIt In AIA");  
  6.     }  
  7. }  

BIA的内容如下:

[java] view plain copy
  1. package spi;  
  2.   
  3. public class BIA implements IA {  
  4.     public void doIt() {  
  5.         System.out.println("doIt In BIA");  
  6.     }  
  7. }  

CIA的内容如下:

[java] view plain copy
  1. package spi;  
  2.   
  3. public class CIA implements IA {  
  4.     public void doIt() {  
  5.         System.out.println("doIt In CIA");  
  6.     }  
  7. }  

Main的内容如下:
[java] view plain copy
  1. package spi;  
  2.   
  3. import java.util.Iterator;  
  4. import java.util.ServiceLoader;  
  5.   
  6. public class Main {  
  7.     public static void main(String[] args) {  
  8.         ServiceLoader<IA> spiLoader = ServiceLoader.load(IA.class);  
  9.         Iterator<IA> iaIterator = spiLoader.iterator();  
  10.         while (iaIterator.hasNext()) {  
  11.             iaIterator.next().doIt();  
  12.         }  
  13.     }  
  14. }  
在META-INF/services/spi.IA文件中的内容如下:
[plain] view plain copy
  1. spi.AIA  
  2. spi.BIA  
  3. spi.CIA  

运行spi.Main,可以发现输出结果如下:


参考文献:

[1]http://singleant.iteye.com/blog/1497259

[2]http://blog.csdn.net/fenglibing/article/details/7083071

0 0
原创粉丝点击