Spicy Spring: Inject your custom method argument in Spring MVC using HandlerMethodArgumentResolver

In Spring MVC we get some method argument types resolved by default and injected in Spring MVC controller methods. Some examples are Model, Locale and OutputStream.
What if we want to inject a custom argument in Spring MVC controller methods? In this example we extract the X-Application-Version HTTP header from the request and inject that as a method argument called version.

Our controller class will look like the following:

This is where we need to write our own HandlerMethodArgumentResolver implementation which is responsible for extracting the X-Application-Version from the HttpHeader.

Now all we need to do is add it as argument resolver by extending the WebMvcConfigurerAdapter and implementing the addArgumentResolvers and add the just created ApplicationVersionMethodArgumentResolver.

2 thoughts on “Spicy Spring: Inject your custom method argument in Spring MVC using HandlerMethodArgumentResolver

  1. Pingback: Add custom HandlerMethodArgumentResolver without having to declare mvc dependency – program faq

  2. Hi Villiam,
    I am having the following issue
    a. In my GET method accountId is visible, while hitting edit action on the form. Account details are visible. In this case user changing accountId on the URL then respective account details are visible. In this case i am using encryption. Now accountId is encrypted if user changing value. Nothing is appeared.
    When as while hitting the edit button, page getting 400-bad request parameter error.
    i found Filter not allowing encrypted value in the url. So, i decided to write CustomHandlerMethodArgumentResolver by implementing HandlerMethodArgumentResolver class. i have done above approach, but my CustomHandlerMethodArgumentResolver.java is not calling.
    Could you please let me know how to write.
    I have done below steps
    1. i have written my own customHandlerArgumentResolver.
    2. supportsParameter override.
    3. resolveArgument override.
    4. entry about CustomHandlerResolver details given in app_servlet.xml file (spring)
    5.

    In this case my own customHandlerResolver is not calling. Where i made mistake.

Leave a Reply

Your email address will not be published. Required fields are marked *