03. 扩展点背景以及JDK提供的扩展点
为什么需要扩展点
因为为了达成能扩展的目的。
更多细节可以阅读oracle官方文档Creating Extensible Applications With the Java Platform
重点:
Definitions
A service is a set of programming interfaces and classes that provide access to some specific application functionality or feature. The service may simply define the interfaces for the functionality and a way to retrieve an implementation. In the word-processor example, a dictionary service can define a way to retrieve a dictionary and the definition of a word, but it does not implement the underlying feature set. Instead, it relies on a service provider to implement that functionality.
A service provider interface (SPI) is the set of public interfaces and abstract classes that a service defines. The SPI defines the classes and methods available to your application.
A service provider implements the SPI. An application with extensible services will allow you, vendors, and perhaps even customers to add service providers without modifying the original application.
目前有什么扩展点机制实现
为了实现扩展,粗略的讲能支持bean容器的框架或机制均可以做扩展点
- JDK自带的扩展点机制,ServiceLoader
- 专门的bean容器:spring、guice等
JDK的扩展点
ServiceLoader:一个简单的服务提供者加载设施。
使用文档与demo可以参见这里官方doc
注意其使用时配置方式是:
If com.example.impl.StandardCodecs is an implementation of the CodecSet service then its jar file also contains a file named
META-INF/services/com.example.CodecSet
This file contains the single line:com.example.impl.StandardCodecs # Standard codecs
简单地说:是将SPI接口的具体实现类的全限定名写入在 META-INF/services目录下以SPI接口全限定名命名的文件中。ServiceLoader能从此文件中知道这个SPI具体选用哪个实现。
自己实现一个扩展点机需要哪些基础能力
根据配置读取相应的实现类并创建实例。
自己实现一个扩展点可以做些什么高阶能力
自动装配(注入)字段、代理、适配、包装、激活(一次获取多个命中实例)等。
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!