HandlerMethodArgumentResolver

HandlerMethodArgumentResolver 사용 방법

프로젝트 구현 중 Pageable을 구현하다가 공통적으로 적용되는 offset, limit 파라미터를 위해 HandlerMethodArguementResolver를 공부하게 되었다.

HandlerMethodArgumentResolver란?

예제 코드


import org.springframework.web.method.support.HandlerMethodArgumentResolver;

import static org.apache.commons.lang3.math.NumberUtils.toInt;
import static org.apache.commons.lang3.math.NumberUtils.toLong;

public class PageableHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

  private Pageable pageable;

  public void setPageable(Pageable pageable) {
    this.pageable = pageable;
  }

  @Override
  public boolean supportsParameter(MethodParameter methodParameter) {
    return Pageable.class.isAssignableFrom(methodParameter.getParameterType());
  }

  @Override
  public Object resolveArgument(MethodParameter methodParameter,
                                ModelAndViewContainer modelAndViewContainer,
                                NativeWebRequest nativeWebRequest,
                                WebDataBinderFactory webDataBinderFactory) throws Exception {
    long offset = toLong(nativeWebRequest.getParameter("offset"), pageable.offset());
    int limit = toInt(nativeWebRequest.getParameter("limit"), pageable.limit());

    return new PageableRequest(offset, limit);
  }
}