1, 什么是ServiceLoader:
A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.------摘自jave API doc
2, 如何使用ServiceLoader:
有一个简单的例子(复杂的原理应该是一样的吧。。。)
1, 新建一个工程ServiceLoaderTest
2, java代码没有什么特别的,一个Interface IMessager和它的一个实现HelloWorld
3, 特别的地方在于META-INF/services/com.wsy.test.IMessager这个文件,首先位置是固定的, META-INF/services, 其次名字是固定的,必须是service(也就是借口)的全限定名,第三内容也是固定的,每行是实现的类名,在这里是com.wsy.test.impl.HelloWorld。如果是多个实现,就写多行,后面我们会看到,可以根据从这些实现中挑选需要需要的
4, 必须要把这个工程打包成jar(没试过war,或者ear,应该也可以吧),我试过在eclipse中让测试工程引用这个工程,貌似是不行的;必须打包,然后加入测试工程的classpath;
5, 在测试工程中可以像如下代码那样使用:
3 后记
貌似这是一个很有趣的功能,面向接口编程,可以在多个实现中选择,而且使用也很方便,不是很繁琐,不需要容器。一个不便之处在于必须要打包才能使用(这个可能是META-INF目录的原因吧,难道这个目录只在jar包里才生效?)。