- Java 9 Dependency Injection
- Krunal Patel Nilang Patel
- 147字
- 2021-08-27 18:49:58
Service (API) module
The created API module with the name com.packt.service.api contains a NotificationService interface to send notification and load service providers. To make this interface a service provider interface (SPI), we have to mention the 'use' clause in module-info.java. Our module code will be as follows:
NotificationService.java
package com.packt.service.api;
import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
public interface NotificationService {
/* Loads all the service providers */
public static List<NotificationService> getInstances() {
ServiceLoader<NotificationService> services = ServiceLoader.load(NotificationService.class);
List<NotificationService> list = new ArrayList<>();
services.iterator().forEachRemaining(list::add);
return list;
}
/* Send notification with provided message and recipient */
boolean sendNotification(String message, String recipient);
}
module-info.java will be as follows:
module com.packt.service.api {
exports com.packt.service.api;
uses com.packt.service.api.NotificationService;
}
The following are the command line steps that need to be followed for the com.packt.service.api module jar. Assume that there will be an out directory in the com.packt.service.api module: