public abstract class InjectionHandler extends Object implements Handler
Subclasses must implement exactly one method named "handle"
that accepts a Context
as the first parameter,
and at least one other parameter of any type.
The handle(Context)
method of this class will delegate to the subclass handle method, supplying values for each parameter
by retrieving objects from the context and request (which are registries).
The context takes precedence over the request.
That is, if the context provides a value for the requested type it will be used regardless of whether the request also provides this type.
The following two handlers are functionally equivalent:
import ratpack.handling.Context;
import ratpack.handling.Handler;
import ratpack.handling.InjectionHandler;
import ratpack.test.embed.EmbeddedApp;
public class Example {
static class Thing {
public final String name;
public Thing(String name) {
this.name = name;
}
}
static class VerboseHandler implements Handler {
public void handle(Context context) {
Thing thing = context.get(Thing.class);
context.render(thing.name);
}
}
static class SuccinctHandler extends InjectionHandler {
public void handle(Context context, Thing thing) {
context.render(thing.name);
}
}
public static void main(String... args) {
EmbeddedApp.fromChain(chain -> chain
.register(r -> r.add(new Thing("foo")))
.get("verbose", new VerboseHandler())
.get("succinct", new SuccinctHandler())
).test(httpClient -> {
assert httpClient.getText("verbose").equals("foo");
assert httpClient.getText("succinct").equals("foo");
});
}
}
If the parameters cannot be satisfied, a NotInRegistryException
will be thrown.
If there is no suitable handle(Context, ...)
method, a InjectionHandler.NoSuitableHandleMethodException
will be thrown at construction time.
Modifier and Type | Class and Description |
---|---|
static class |
InjectionHandler.NoSuitableHandleMethodException
Exception thrown if the subclass doesn't provide a valid handle method.
|
Modifier | Constructor and Description |
---|---|
protected |
InjectionHandler()
Constructor.
|
Modifier and Type | Method and Description |
---|---|
void |
handle(Context context)
Invokes the custom "handle" method, extracting necessary parameters from the context to satisfy the call.
|
protected InjectionHandler() throws InjectionHandler.NoSuitableHandleMethodException
InjectionHandler.NoSuitableHandleMethodException
- if this class doesn't provide a suitable handle method.