If we write our own handler class it is not so difficult to get objects from the registry and use them in the code. In our handler we have a handle method and we get a Context object as argument. From the Context we get access to objects in the registry. Instead of writing code to get the objects from the registry we can use the InjectionHandler as superclass for our handler. The InjectionHandler class has a handle method that will look for a handle method in our implementation class with a first argument of type Context. Then at least one other argument must be defined in the method signature. The types of the other arguments are used to get the corresponding objects from the registry. We don't write the code to get the object from the registry ourselves, but rely on the implementation in the InjectionHandler class.

The following example handler class extends from the InjectionHandler. We write a handle method and from the signature we see that we have a dependency on the type Messages. In the implementation of the handle method we can rely on the InjectionHandler class to get an object from the registry with type Messages.

package com.mrhaki.ratpack

import ratpack.handling.Context
import ratpack.handling.InjectionHandler

 * Extend from InjectionHandler. The InjectionHandler
 * has a handle method implementation that will
 * look for a handle method in this implementing class
 * and uses the argument types to get object from the
 * registry.
class MessagesHandler extends InjectionHandler {

     * New (not overriden) handle method where
     * the first argument must be a Ratpack Context.
     * The next arguments are of types
     * that are available on the registry.
     * @param context Ratpack context to interact with.
     * @param messages Messages to return a message.
    void handle(final Context context, final Messages messages) {
        // An instance of Messages is already available
        // thanks to the InjectionHandler superclass.


Written with Ratpack 1.1.1.

Original blog post