The services concepts covered so far should address a lot of typical use cases, but there are a few additional features and concepts that might come in handy in certain special scenarios. We'll look at a few such concepts in this section.
Suppose your service instances cannot be created simply by a constructor. What if you need to reuse instances, maybe to have a singleton provider instance? Or maybe execute some logic whenever a new service instance is created? There is a handy feature of services that lets you create factory methods to get service instances. All you need to do is add a method with the name provide()
in your provider classes. The method needs to be a public static method and it shouldn't take any arguments. Also, the return type should be the same as the type of the service being provided. If the ServiceLoader
sees this method, it calls it, and uses the return of the method as the service instance. If it doesn't...