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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • JGit Library Examples in Java
  • Spring Boot - Custom Password Validator Using Passay Library
  • How to Marry MDC With Spring Integration
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers

Trending

  • Reducing Hallucinations Using Prompt Engineering and RAG
  • Vibe Coding: Conversational Software Development — Part 1 Introduction
  • Docker Model Runner: A Game Changer in Local AI Development (C# Developer Perspective)
  • Lessons Learned in Test-Driven Development
  1. DZone
  2. Coding
  3. Frameworks
  4. Extensible Libraries With ServiceLoader and Spring

Extensible Libraries With ServiceLoader and Spring

The notion of extensible libraries has been around quite a while. Here's an overview of extensible libraries with Spring and ServiceLoader, with awesome inclusions like creating an API.

By 
Michał Minicki user avatar
Michał Minicki
·
Feb. 05, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
9.8K Views

Join the DZone community and get the full member experience.

Join For Free

The concept of extensible libraries is not new and is called by many different names depending on which context it is used in, like pluggable architecture or a factory finder pattern. You're already familiar with it if you ever needed to write a library allowing your users to extend its functionality at runtime.

One example of such a library is a quite popular SLF4J logging framework and its bindings. When you're writing a reusable library intended to be vended to others, SLF4J is a good bet. It provides an API you use in your own application code but allows your users to choose any logging implementation they wish to use, like System.out (slf4j-simple), Log4j (slf4j-log4j), or even lets them not to log anything (slf4j-noop). This is the major reason why libraries like Hibernate chose SLF4J over other logging systems.

If you ever wanted to write a library like SLF4J you would need such a pluggable system yourself. The good news is Java itself uses that kind of architecture internally and exposed its mechanism for you to use with the ServiceLoader system (since version 6). Even better, it's simple and easy to use. You're required to create an API and then load all implementations with Java provided classes. The whole concept is well documented in the following tutorial on Oracle's pages - Creating Extensible Applications. 

Here's how it looks in a nutshell.

You create an API:

public interface Dictionary {

     public String getDefinition(String word);

}

Then load all implementations:

public class DictionaryService {

    private ServiceLoader<Dictionary> loader;

    public DictionaryService() {
       loader = ServiceLoader.load(Dictionary.class);
    }

}

And finally use them:

for (Dictionary dictionary : this.loader) {

    String definition = dictionary.getDefinition(word);

    if (definition != null) {
        return definition;
    }

}

If you ever want to use a ServiceLoader with Spring you don't have to create ServiceLoader beans yourself.  In order to make the Oracle's example usable let's modify the DictionaryService to accept Dictionary loader implementations in the constructor instead:

public class DictionaryService {

    private ServiceLoader<Dictionary> loader;

    public DictionaryService(ServiceLoader<Dictionary> loader) {
        this.loader = loader;
    }

}

Now, let's modify the DictionaryDemo class to use Spring instead of instantiating DictionaryService ourselves:

public class DictionaryDemo {

    private static ApplicationContext ctx = 
        new AnnotationConfigApplicationContext(DictionaryAppConfiguration.class);

    public static void main(String[] args) {

        DictionaryService dictionary = ctx.getBean(DictionaryService.class);

        System.out.println("Book: " + dictionary.getDefinition("book"));

    }

} 

Finally, let's make Spring do its magic in the DictionaryAppConfiguration class:

@Configuration

public class DictionaryAppConfiguration {    

    @Bean
    public DictionaryService dictionaryService(ServiceLoader<Dictionary> loader) {
        return new DictionaryService(loader);
    }

    @Bean
    public ServiceLoaderFactoryBean dictionaryServiceLoaderFactory() {
        ServiceLoaderFactoryBean factoryBean = new ServiceLoaderFactoryBean();
        factoryBean.setServiceType(Dictionary.class);
        return factoryBean;
    }

}

There you go, nice and easy. 

Unfortunately, this creates a problem - as you might have guessed, the ServiceLoader requires your Dictionary implementation to have a no argument constructor. Nothing in the real world is that easy and this kind of design would force you to use static Service Locator patterns (and you know it's bad). Ideally, you would use a dependency injection framework (like Spring Framework) which allows you to inject your Dictionary classes with external collaborators. An example of such collaborator would be a database repository used to load your word definitions from a database. For that, we would need a different solution but that's a story for another time. 

Spring Framework Library

Opinions expressed by DZone contributors are their own.

Related

  • JGit Library Examples in Java
  • Spring Boot - Custom Password Validator Using Passay Library
  • How to Marry MDC With Spring Integration
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers

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
  • [email protected]

Let's be friends: