Home  >  Core Java

ServiceLoader Java Example

By Arvind Rai, August 24, 2013
A service can be an interface or abstract class. ServiceLoader provides the flexibility to load different implementation of a service. Letís a service is CPService. This will be an interface. Now according to the requirement there can be more than one implementation of CPService. Find the implementation classes in CPService interface.

CPService.java
package com.concretepage.util;
public interface CPService {
    public void show();
}
 


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....");
    }
}
 
First we will 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 in the file com.util.CPService created inside services folder as 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 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. For the flexibility purpose to load different services for different client, becomes easy in this way.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us