10 Using services to decouple modules

 

This chapter covers

  • Improving project designs with services
  • Creating services, consumers, and providers in the JPMS
  • Using the ServiceLoader to consume services
  • Developing well-designed services
  • Deploying services in plain and modular JARs across different Java versions

Up to now, we represented relationships between modules with requires directives where the depending module has to reference each specific dependency by name. As section 3.2 explains in depth, this lies at the heart of reliable configuration. But sometimes you want a higher level of abstraction.

This chapter explores services in the module system and how to use them to decouple modules by removing direct dependencies between them. The first step to solving any problems with services is to get the basics down. Following that, we look at the details, particularly how to properly design services (section 10.3) and how to use the JDK’s API to consume them (section 10.4). (To see services in practice, check out the feature-services branch in ServiceMonitor's repository.)

By the end of this chapter, you’ll know how to design services well, how to write declarations for modules that use or provide services, and how to load services at run time. You can use these skills to connect with services in the JDK or third-party dependencies as well as to remove direct dependencies in your own project.

10.1 Exploring the need for services

10.2 Services in the Java Platform Module System

10.2.1 Using, providing, and consuming services

10.2.2 Module resolution for services

10.3 Designing services well

10.3.1 Types that can be services

10.3.2 Using factories as services

10.3.3 Isolating consumers from global state

10.3.4 Organizing services, consumers, and providers into modules

10.3.5 Using services to break cyclic dependencies

10.3.6 Declaring services across different Java versions

10.4 Accessing services with the ServiceLoader API

10.4.1 Loading and accessing services

10.4.2 Idiosyncrasies of loading services

Summary

sitemap