springboot 自定义注解 结合springMVC 处理方法中接收的参数

在最近做的项目中, 遇到一个问题 , 需要使用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);
    }
}

这样就完成了对方法参数进行处理. 有不妥之处 还望请教.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

漫长的~以后

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值