自定义Controller方法参数解析器

  • 2019 年 12 月 19 日
  • 笔记

自定义Controller方法参数注入,比如主动注入当前用户等等

核心类:HandlerMethodArgumentResolver

package org.springframework.web.method.support;    import org.springframework.core.MethodParameter;  import org.springframework.lang.Nullable;  import org.springframework.web.bind.WebDataBinder;  import org.springframework.web.bind.support.WebDataBinderFactory;  import org.springframework.web.context.request.NativeWebRequest;    /**   * Strategy interface for resolving method parameters into argument values in   * the context of a given request.   *   * @author Arjen Poutsma   * @since 3.1   * @see HandlerMethodReturnValueHandler   */  public interface HandlerMethodArgumentResolver {       /**      * Whether the given {@linkplain MethodParameter method parameter} is      * supported by this resolver.      * @param parameter the method parameter to check      * @return {@code true} if this resolver supports the supplied parameter;      * {@code false} otherwise      */     boolean supportsParameter(MethodParameter parameter);       /**      * Resolves a method parameter into an argument value from a given request.      * A {@link ModelAndViewContainer} provides access to the model for the      * request. A {@link WebDataBinderFactory} provides a way to create      * a {@link WebDataBinder} instance when needed for data binding and      * type conversion purposes.      * @param parameter the method parameter to resolve. This parameter must      * have previously been passed to {@link #supportsParameter} which must      * have returned {@code true}.      * @param mavContainer the ModelAndViewContainer for the current request      * @param webRequest the current request      * @param binderFactory a factory for creating {@link WebDataBinder} instances      * @return the resolved argument value, or {@code null} if not resolvable      * @throws Exception in case of errors with the preparation of argument values      */     @Nullable     Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,           NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception;    }

这个接口中有两个方法,supportsParameter用于判断是否通过本解析器解析该参数,resolveArgument用于编写解析的逻辑,返回的对象赋值给方法的相对应的参数。

举个例子

import lombok.Data;    /**   * @author donghaibin   */  @Data  public class User {        private String name;        private String age;  }

一个User对象,现在需要在Controller的一个接口中获取当前请求的User,最直接的方法是在方法体中编写逻辑获取,但这样写不是那么的优雅。另一种方法就是通过HandlerMethodArgumentResolver实现。

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;    /**   * @author donghaibin   */  public class UserArgumentResolver implements HandlerMethodArgumentResolver {        @Override      public boolean supportsParameter(MethodParameter methodParameter) {          // isAssignableFrom方法判断类型是否为本身或者子类          return methodParameter.getParameterType().isAssignableFrom(User.class);      }        @Override      public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {          // 这里测试直接构建一个对象返回          User user = new User();          user.setAge("18");          user.setName("DHB");          return user;      }    }
import org.springframework.context.annotation.Configuration;  import org.springframework.web.method.support.HandlerMethodArgumentResolver;  import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;    import java.util.List;    /**   * @author donghaibin   */  @Configuration  public class WebMvcConfig implements WebMvcConfigurer {        @Override      public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {          // 添加进参数解析器集合          resolvers.add(new UserArgumentResolver());      }  }

测试

import cn.dhbin.test.config.User;  import cn.dhbin.test.config.UserFlag;  import lombok.extern.slf4j.Slf4j;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RestController;    /**   * @author donghaibin   */  @RestController  @Slf4j  public class TestController {        @RequestMapping("/test")      public String test(String a, User user) {          log.info(user.toString());          return a;      }  }

结果

2019-07-18 23:47:14.535  INFO 44852 --- [nio-8080-exec-1] cn.dhbin.test.controller.TestController  : User(name=DHB, age=11)

总结

通过这个demo大概明白自定义参数解析只需两步

  1. 继承HandlerMethodArgumentResolver编写解析逻辑
  2. 重写WebMvcConfigurer的addArgumentResolvers方法,添加自定义的解析器到参数解析器集合中