SPI的全名为Service Provider Interface
不就是spring吗?
接口定义
public interface Search { void search(String keyword); }
实现类1
public class FileSearch implements Search { public void search(String keyword) { System.out.println("file: " + keyword); } }
实现类2
public class DatabaseSearch implements Search { public void search(String keyword) { System.out.println("database: " + keyword); } }
主函数
public static void main(String[] args) { ServiceLoader<Search> s = ServiceLoader.load(Search.class); Iterator<Search> searchs = s.iterator(); if (searchs.hasNext()) { Search curSearch = searchs.next(); curSearch.search("test"); }else{ System.out.println("end"); } }