Java 9 Dependency Injection
上QQ阅读APP看书,第一时间看更新

Service provider (Implementation) module

Now, create a service provider module com.packt.service.impl to implement NotificationService service API, and for that we should define a "provides ... with" clause in the module-info.java file. The provides keyword is used to mention the service interface name and the with keyword is used to mention which implementation we want to load. In the event that the module doesn’t have the provides statement in the module descriptor file, the service loader will not load that module. The syntax of the 'provides...with' statement is as follows:

provides <service-interface> with <service-implementation>

To send an SMS message to a recipient we are creating two implementation classes, SMSServiceImpl.java  and EmailServiceImpl, by implementing  NotificationService:

SMSServiceImpl.java

package com.packt.service.impl;

import com.packt.service.api.NotificationService;

public class SMSServiceImpl implements NotificationService {

public boolean sendNotification(String message, String recipient) {
// Code to send SMS
System.out.println("SMS has been sent to Recipient :: " + recipient + " with Message :: "+message);
return true;
}
}

The module descriptor for this provider module will be as follows:

module-info.java

module com.packt.service.impl {
requires com.packt.service.api;
provides com.packt.service.api.NotificationService with com.packt.service.impl.SMSServiceImpl;

}

To generate a jar file of the com.packt.service.impl module, we have to copy notification-api.jar of the service API module into the lib folder for compile time dependency resolution. The outcome of the following commands will be sms-service.jar:

Service Provider Rules:

  • It always has a no-argument constructor. This constructor is used by the ServiceLoader class to instantiate the service provider using reflection.
  • The provider must be a public concrete class. It should not be an abstract class or inner class.
  • An occurrence of the implementation class must be consistent with the service interface.