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

  • JGit Library Examples in Java
  • 6 Techniques To Reduce LLM API Costs With the Python Library
  • Runtime Formula Evaluation With MVEL Library in Spring Boot
  • C/C++ Is Where Vulnerability Programs Go to Guess

Trending

  • How to Build Your Own AI SRE From Scratch
  • Introduction to Error Prone: How to Catch Bugs at Compile Time
  • Why AI Agents Need a Shared Enterprise Ontology
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine

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. 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
·
Feb. 05, 16 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
10.4K 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

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
  • 6 Techniques To Reduce LLM API Costs With the Python Library
  • Runtime Formula Evaluation With MVEL Library in Spring Boot
  • C/C++ Is Where Vulnerability Programs Go to Guess

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