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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Dependency Injection
  • Tackling Records in Spring Boot
  • Singleton: 6 Ways To Write and Use in Java Programming

Trending

  • Build a Voice Assistant With Gemini Live API
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • SSRF Prevention in C#: Securing File Imports From User-Supplied URLs

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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.

By 
Harmeet Singh(Taara)
·
Oct. 02, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
36.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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.

Related

  • Dropwizard vs. Micronaut: Unpacking the Best Framework for Microservices
  • Dependency Injection
  • Tackling Records in Spring Boot
  • Singleton: 6 Ways To Write and Use in Java Programming

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook