Java 9 Dependency Injection
上QQ阅读APP看书,第一时间看更新

Modules with Service Loader

A service is a bunch of interfaces and classes collectively named a library, which delivers a specific functionality. Simply, we can say API. There are multiple usages for a service and they are called service providers (say implementations) . The client utilizing this service will not have any contact with the implementations. This can be accomplished by utilizing the underneath concept.

Java has ClassLoader, which simply loads the classes and creates instances of classes on runtime. Compared to Java 9 modules, java.util.ServiceLoader is capable of finding and loading all the service providers at a runtime for a service interface. The ServiceLoader class permits decoupling between the API and client app. The service loader will instantiate all the service providers that are implementing the service and makes it accessible to the client to utilize.

Let's take an example of Notification Application containing API and a different implementation of API. We will create three modules, the first one with a service (API) module, the second one will be a provider (Implementation) module, and the last one will be a client module for the accessing service.