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:

@RestController
public class MyController {

    @RequestMapping("/persons")
    //I want the version to be automatically injected
    public List getPersons(String version) {
        .....
        return someList;
    }
} 

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

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class ApplicationVersionMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(String.class)
        && parameter.getParameterName().equals("version");
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        return webRequest.getHeader("X-Application-Version");
    }
}

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.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class MyWebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addArgumentResolvers(List argumentResolvers) {
        argumentResolvers.add(new ApplicationVersionMethodArgumentResolver());
    }
}
shadow-left