Service Provider Interface: Creating Extensible Java Applications, Page 3
The Service Provider Demo
This section demonstrates how users would load and use the service provider. To use the Weather service provider, you need to add the provider JAR to the application classpath. If you are using Eclipse, you could add the provider JAR to the Build Path.
Figure 4 shows a class diagram that describes the classes involved.
Figure 4. Class Diagram of Service Provider Demo: To use the Weather service provider, you need to add the provider JAR to the application classpath.
The WeatherService class follows the Singleton pattern. It implements the Weather SPI specification to adopt the Weather SPI but delegates the calls to retrieve the weather info to the actual provider. Thus, it acts as representative/proxy to the service provider WeatherServiceProvider. It uses the ServiceLoader API to load the provider(s) (more than one provider could exist for the same SPI specification). By iterating through the cache of the loader, it picks up the first loaded and instantiated provider. This approach provides a level of indirection between the providers and users and thus accomplishes loose coupling between the concrete providers and the users. The following code snippet demonstrates the iteration logic:
If you were to create a new provider for the Weather SPI, all you'd need to do is follow the pattern for WeatherServiceProvider:
- Finish coding the new Weather provider.
- Add the name of the concrete class as the contents to the binary file (com.weather.spi.Weather) to reflect the new concrete class.
- Create a new JAR and add it to the application classpath.
The code that used the providers will remain unchanged. The ServiceLoader API allows users to add new implementations to their applications as they become available, thus paving the way to extensibility and modularity.
The following code snippet demonstrates how to use WeatherService:
You now have completed a demonstration of a service provider that fulfills the SPI specification. You have also seen how to use the ServiceLoader API as an approach for creating extensible applications. SPI is a starting place for building extensible applications. It could even be extended to support more recent concepts such as the service-oriented architecture using web services. For instance, you could add translation logic to WeatherService to convert the return response of getCurrentWeather() into XML using JAXB.
About the AuthorThribhuvan Thakur is a senior software engineer and Technical Lead at Southwest Airlines with 12 years of experience in design and development in J2EE. He has been working with Java since its inception, and with JMS since 1999. Thakur is a Sun Certified Java Programmer, Sun Certified Java Developer, and Sun Certified J2EE Architect. He holds a Masters in Computer Science from the University of North Texas.