Make Spring MVC work for you: injecting custom method arguments

Marcos Abel
Trabe
Published in
2 min readOct 22, 2018
Photo by John Carlisle on Unsplash

Making a clever library/framework work for you is usually a good idea . Some weeks ago we talked about the benefits of code generation and how project Lombok can help us write and maintain less code. Today we are exploring Spring MVC’s HandlerMethodArgumentResolver and the advantages that its use can provide.

What are we trying to achieve?

When you use Spring MVC you can add certain arguments to your controller methods and the framework injects those arguments for you:

In the snippet above request, model and locale are effortlessly provided to us by the framework. We don’t need to expend time and lines of code retrieving them and we can just focus on our business logic.

The good news is that Spring MVC provides us with the tools we need to use this magic to support our own custom arguments.

An example please!

Let’s say we have an application that deals with devices. A device is, in this context, something like this:

Our application provides an API with plenty of device related methods. The endpoints include the device id in the path and in almost every method we need to retrieve the Device by id and then do something with it:

We transform our controller methods including a Device parameter and removing the code devoted to retrieve the Device:

The code savings here in this example are not massive, but in real world applications they can be much bigger.

In the rest of the story we will explain how to configure our Spring MVC application to properly inject the Device parameter for us.

Injecting custom arguments

Spring MVC provides us with an interface designed to allow us to inject parameters to our controller methods: HandlerMethodArgumentResolver. In order to have custom arguments injected for us, we implement the interface:

The first thing to note about this implementation is the supportsParameter method: we need to return true for the parameters we want to resolve in our resolver. In this case we just resolve parameters of Device class.

The second overridden method,resolveArgument, is where the magic happens. We retrieve the pathVariables for the current request and then use deviceService to get and return our device.

The only thing left is configuring Spring to make use of our attribute resolver. Depending in our infrastructure, we can do it using xml or code configuration:

Old good XML configuration
Code configuration

From now on, Spring will inject the correct device for us in any controller method with a deviceId path variable and a parameter of type Device.

Wrapping up

Taking advantage of argument injection can make a big difference in real world applications. Framework features like this one enable us to remove boilerplate and keep our codebase clean and focused on its main responsibilities.

--

--