在最近做的项目中, 遇到一个问题 , 需要使用post 提交参数 , 然后用
@RequestBody
进行后端参数的接收 , 但是接收的参数是JSON格式的 , 接收之后还需要转成对象,这就有点麻烦. 所以决定用自定义注解对参数先进行处理,再传入. 下面介绍我的步骤:
首先自定义一个注解:
/**
* 接收json数据格式的参数, 转换成对象
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@Documented
public @interface GetJsonValue {
public String value() default "";
}
其中注解的上面的元注解我就不一一介绍了, 网上有很多关于元注解的资料. 我就简单说明一下我这个注解
@Target(ElementType.PARAMETER)
作用域为 参数
public String value() default “”;
定义一个 value属性 默认值为空
接着创建一个类 实现 HandlerMethodArgumentResolver 接口, 作用是拦截具体方法 , 对方法参数进行业务处理.
@Configuration
public class HandlerParameterResolver implements HandlerMethodArgumentResolver {
/**
* 此方法拦截加了注解的参数 方法
* @param methodParameter
* @return
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
//拦截添加注解的方法参数
if(methodParameter.hasParameterAnnotation(GetJsonValue.class)){
return true;
}
return false;
}
/**
* 对加了自定义注解的方法进行业务操作
* @param methodParameter
* @param modelAndViewContainer
* @param nativeWebRequest
* @param webDataBinderFactory
* @return
* @throws Exception
*/
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
//获取注解的属性值
String value = methodParameter.getParameterAnnotation(GetJsonValue.class).value();
//获取request
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
//获取request里面json格式数据,转换成map ,JsonUtil是自己写的一个转换类
Map<String,Object> json = JsonUtil.getRequestJsonObject(request);
return json.get(value);
}
}
然后创建一个类,继承 WebMvcConfigurerAdapter 实现其 addArgumentResolvers 方法 把我们刚刚创建的类注入其中
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
//注册到spring容器中
@Resource
private HandlerParameterResolver handlerParameterResolver;
//添加对方法的拦截
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(handlerParameterResolver);
super.addArgumentResolvers(argumentResolvers);
}
}
这样就完成了对方法参数进行处理. 有不妥之处 还望请教.