JAVA的SPI机制

       SPI : Service Provider Interface : 服务提供接口。

  JavaSPI 实际上是“基于接口的编程+策略模式+配置文件”组合实现的动态加载机制。

       具体而言:

       STEP1. 定义一组接口, 假设是Person;

       STEP2. 写出接口的一个或多个实现(Woman或者Man);

       STEP3. 在 src/main/resources/ 下建立 /META-INF/services 目录, 新增一个以接口命名的文件 Person, 内容是要应用的实现类(Woman或者Man 或两者);

       STEP4. 使用 ServiceLoader 来加载配置文件中指定的实现。 

public class PersonTest {

    public static void main(String[] args) {
        ServiceLoader matcher = ServiceLoader.load(Person.class);
        Iterator matcherIter = matcher.iterator();
        while (matcherIter.hasNext()) {
            Person personMatcher = matcherIter.next();
            System.out.println(personMatcher.getClass().getName());
            personMatcher.doSomething(); 
        }

    }
}

自定义ClassLoad

public class MyServiceLoader {

    private static final String PREFIX = "/META-INF/services/";

    public static  List load(Class cls) {
        List implClasses = readServiceFile(cls);
        List implList = new ArrayList();
        for (String implClass : implClasses) {
            Class c = null;
            try {
                c = (Class) Class.forName(implClass);
                implList.add(c.newInstance());
            } catch (Exception e) {
                return new ArrayList();
            }
        }
        return implList;
    }

    private static List readServiceFile(Class cls) {
        String infName = cls.getCanonicalName();
        String fileName = cls.getResource(PREFIX+infName).getPath();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new File(fileName)));
            String line = "";
            List implClasses = new ArrayList();
            while ((line = br.readLine()) != null) {
                implClasses.add(line);
            }
            return implClasses;
        } catch (FileNotFoundException fnfe) {
            System.out.println("File not found: " + fileName);
            return new ArrayList();
        } catch (IOException ioe) {
            System.out.println("Read file failed: " + fileName);
            return new ArrayList();
        }
    }

   
}

 

你可能感兴趣的:(java)