In most of the applications we are using Dependency Injection for loosely couple of our code. Some time, we just require simple DI, nothing else, for those, we need to include some of our DI frameworks like Spring, Google Guice etc. This makes our project jar heavy and added some unnecessary classes as well. For all these, Java itself have a ServiceLoader class for inject your dependency at run time. ServiceLoader had introduce in JDK 3, but this is used for internal purpose. During JDK 6, this class scopes to public but still, it is a final class, we are not able to extends its functionality.

ServiceLoader will play important role in JDK 9, Which we will discuss in our next post. Today, we are creating a simple Greetings application using ServiceLoader as below:

Step I: Prerequisite

JDK >= 6

Maven

Step II:

Creating an abstract layer for any service, which implementation decide and runtime like below code:

Note: For loading GreetingService we are using ServiceLoader , If GreetingsService have multiple implementation, the ServiceLoader will load all of its implementation, this depends on us, how we can handle implementations. In above code, i am assuming only one implementation and find out using next().

Step IV:

Creating a directory META-INF/service on your classpath. That directory contains a file with full qualified name of your abstract service class like