DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Play With Java ServiceLoader And Forget About Dependency Injection Frameworks

Play With Java ServiceLoader And Forget About Dependency Injection Frameworks

Using Java SPI to load dependencies for Play Framework code using regular Java. No extra libraries or dependencies to add to your build.

Harmeet Singh(Taara) user avatar by
Harmeet Singh(Taara)
·
Oct. 02, 16 · Tutorial
Like (12)
Save
Tweet
Share
32.33K Views

Join the DZone community and get the full member experience.

Join For Free

In most of our applications, we are using Dependency Injection to loosely couple of our code. Sometimes, 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 has a ServiceLoader class to inject your dependency at runtime.

ServiceLoader was introduced in JDK 3, but this is used for internal purposes. 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 an important role in JDK 9, which we will discuss in our next post. Today, we are creating a simple Greetings application using ServiceLoader.

Step 1: Prerequisite

  • JDK >= 6

  • Maven

Step 2: Abstract Layer

Create an abstract layer for any service.

package com.knoldus.service;

public interface GreetingsService {
    void sayHello(String name);
}


Create an implementation of the service by implementing the interface as below:

package com.knoldus.service.impl;

import com.knoldus.service.GreetingsService;

public class ConsoleGreetings implements GreetingsService {
    @Override
    public void sayHello(String name) {
        System.out.println("Hello to "+name);
    }
}


Step 3: Define the Provider

Now we need to define our provider, which loads the GreetingsService implementation at runtime and creates an instance to it.

import java.util.ServiceLoader;

public class GreetingsProvider {
    private static GreetingsProvider provider;
    private ServiceLoader<GreetingsService> loader;

    private GreetingsProvider() {
        loader = ServiceLoader.load(GreetingsService.class);
    }

  public static GreetingsProvider getInstance() {
      if(provider == null) {
          provider = new GreetingsProvider();
      }

      return provider;
    }

    public GreetingsService serviceImpl() {
        GreetingsService service = loader.iterator().next();

        if(service != null) {
            return service;
        } else {
            throw new NoSuchElementException(
            "No implementation for GreetingsProvider");
        }
    }
}


Note: To load GreetingService, we are using ServiceLoader. If GreetingsService has multiple implementations, the ServiceLoader will load all of them. This depends on us and how we can handle implementations. In the above code, I am assuming there is only one implementation and finding out using next().

Step 4: Create a Directory

Creating a directory (META-INF/service) on your classpath. That directory contains a file with the fully qualified name of your abstract service class, like com.knoldus.service.GreetingsService.

This files contains the details of its implementation: com.knoldus.service.impl.ConsoleGreetings.

Step 5: Create a Main Class

Create a main class for the code execution as below:

package com.knoldus.main;

import com.knoldus.providers.GreetingsProvider;
import com.knoldus.service.GreetingsService;

public class Launcher {
    public static void main(String... args) {
        GreetingsService service = GreetingsProvider.getInstance().serviceImpl();
        service.sayHello("Knoldus");
    }
}

References:

https://docs.oracle.com/javase/tutorial/ext/basics/spi.html

Dependency injection Java (programming language)

Published at DZone with permission of Harmeet Singh(Taara). See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Remote Debugging Dangers and Pitfalls
  • What Should You Know About Graph Database’s Scalability?
  • Cloud-Native Application Networking
  • Why Does DevOps Recommend Shift-Left Testing Principles?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: