java ServiceLoader sample

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包里才生效?)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值