Edit Page

Providers

RESTHeart

Provider classes in RESTHeart work together with the @Inject and @OnInit annotations to form a Dependency Injection mechanism.

The Provider class

A Provider class must implements the interface Provider and must be annotated with @RegisterPlugin:

RegisterPlugin(name="hello-world-message", description="a dummy provider")
class MyProvider implements Provider<String> {
    @Override
    public String get(PluginRecord<?> caller) {
        return "Hello World!";
    }
}

Given the hello-world-message provider, we can inject its provided object into any Plugin with the @Inject annotation:

@RegisterPlugin(name = "greetings", description = "just another Hello World")
public class GreeterService implements JsonService {
    @Inject("hello-world-message")
    private String message;

    @OnInit
    public void init() {
        // called after all @Inject fields are resolved
    }

    @Override
    public void handle(JsonRequest req, JsonResponse res) {
        switch(req.getMethod()) {
            case GET -> res.setContent(object().put("message", message));
            case OPTIONS -> handleOptions(req);
            default -> res.setStatusCode(HttpStatus.SC_METHOD_NOT_ALLOWED);
        }
    }
}

@RegisterPlugin annotation

The following table describes the arguments of the annotation:

param description mandatory default value

name

the name of the provider

yes

none

description

description of the provider

yes

none

Optional Dependencies

By default, @Inject declares a required dependency: if the provider is not found or is disabled, the plugin itself is disabled at startup.

To declare an optional dependency, set required = false. When the provider is missing, the field is set to null and the plugin remains enabled. A DEBUG log is emitted.

@RegisterPlugin(name = "myPlugin", description = "...")
public class MyPlugin implements JsonService {

    @Inject(value = "emails", required = false)
    private EmailSender emailSender;

    @OnInit
    public void init() {
        if (emailSender == null) {
            // fallback: notifications disabled
        }
    }
}
Note
Available from version 9.8

The required parameter was introduced in RESTHeart 9.8. In earlier versions, optional dependencies required a manual lookup via PluginsRegistry.getProviders().

This is useful when a plugin can function without a particular provider — for example, a billing service that optionally sends email notifications.