spi

Posted by Xsp on December 24, 2018

demo

目录结构

// Cat.java
package spi;

public class Cat implements IShout {
    @Override
    public void shout() {
        System.out.println("miao miao");
    }
}
// Dog.java
package spi;

public class Dog implements IShout {
    @Override
    public void shout() {
        System.out.println("wang wang");
    }
}
// 接口类
package spi;

public interface IShout {
    void shout();
}
// resources/META-INF/services/spi.IShout 文件
spi.Cat
spi.Dog
// 测试
package spi;

import java.util.ServiceLoader;

public class SPIMain {
    public static void main(String[] args) {
        ServiceLoader<IShout> shouts = ServiceLoader.load(IShout.class);
        for (IShout s : shouts) {
            s.shout();
        }
    }
}
// 运行结果
// miao miao
// wang wang

参考