Java ServiceLoader Example

By Arvind Rai, November 17, 2023
Java ServiceLoader provides the flexibility to load different implementation of a services.
Suppose we have a service class i.e. CPService as an interface. As we know that there can be more than one implementation of CPService.
Find the CPService interface.
CPService.java
package com.concretepage.util;
public interface CPService {
    public void show();
} 
Find the implementations of CPService interface.
CPServiceImplOne.java
package com.concretepage.util;
public class CPServiceImplOne implements CPService {
    @Override
    public void show(){
        System.out.println("CPServiceImplOne has been loaded....");
    }
} 
CPServiceImplTwo.java
package com.concretepage.util;
public class CPServiceImplTwo implements CPService {
    @Override
    public void show(){
        System.out.println("CPServiceImplTwo has been loaded....");
    }
} 
Let us load CPServiceImplOne.java. We need to create a folder structure META-INF/services inside our classpath and then create a file with fully qualified Service name. The structure will look like
META-INF
 --- services
      ---- com.util.CPService
 
We need to mention service implementation class name as com.util.concretepage.CPServiceImplOne in the file com.util.CPService created inside services folder.
META-INF/services/com.util.CPService
com.util.concretepage.CPServiceImplOne 
Now run main method to load Service.
ServiceLoaderDemo.java
package com.concretepage.util;
import java.util.ServiceLoader;

public class ServiceLoaderDemo {
  public static void main(String[] args) {
      ServiceLoader<CPService> serviceLoader =
              ServiceLoader.load(CPService.class);
      for (CPService cpService : serviceLoader) {
          cpService.show();
      }
  }
} 
Output:
CPServiceImplOne has been loaded....
If we configure com.util.concretepage.CPServiceImplTwo then output will be
CPServiceImplTwo has been loaded....
Service implementation can be provided in jar too and can be kept in classpath.
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us