Monday, May 22, 2017

Spring MVC's ArgumentResolver


Recently a colleague introduced to me the concept of an ArgumentResolver.

In theory, with an ArgumentResolver, one can inject anything into a Spring MVC Controller. They are usually injected as arguments (aka parameters) in the Controller's methods.



So first in the XML configuration we do the below:


    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="com.mycompany.ArgumentResolver"></bean>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>



Then we implement the class itself:

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

public class ArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().equals(MyClass.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        // do what you need to return the Argument
        
    }
}




No comments:

Post a Comment