Java Service Provider Interface (SPI)
Thursday, March 19th, 2009Long time ago, I had a bad time trying to develop a “plugin mechanism” to my “open source Toad“. What I didn’t know is how to use the service provider infrastructure avaliable since Java 1.3 (what a shame!).
If you want to create a service provider interface (SPI):
- Define an interface or abstract class (this will be implemented/overrided by the provider)
- Use “ServiceLoader.load” when you need the concrete instances (it’s an iterator that can be used in a “foreach”)
If you want to provide a service (the plugin itself):
- Implement/override the code of SPI
- Create a META-INF/services folder
- Create a file with the same name of the SPI class and add the name of the concrete classes from step 1
And we are done! A simple, yet robust, solution to add extensibility.