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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  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) user avatar
Harmeet Singh(Taara)
·
Oct. 02, 16 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
35.3K 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.

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

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: