Posts Tagged ‘spi’

Java Service Provider Interface (SPI)

Thursday, March 19th, 2009

Long 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):

  1. Define an interface or abstract class (this will be implemented/overrided by the provider)
  2. 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):

  1. Implement/override the code of SPI
  2. Create a META-INF/services folder
  3. 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.