java注解形式实现自定义参数解析器,为方法中的参数注入值

1. 需求概述

观察以下demo代码,方法queryByCondition有两个传入参数,其中,只有id为前端传过来的,但是service还需要phone这个参数,在代码中还有很多类似的功能,如果每个接口都编写代码获取phone的值,会造成大量重复代码,影响工作效率。因此,本文通过java自定义注解的形式实现自定义参数解析器,为方法中的参数注入值。

	@GetMapping("/{id}")
    public RespResult queryByCondition(@PathVariable("id") Long id, String phone){
		xxxService.queryByCondition(id, phone);
		// return语句
    }

2. 代码实现

  1. 自定义注解
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserPhone {
}
  1. 定义参数解析器
@Component
public class UserPhoneArgumentResolver implements HandlerMethodArgumentResolver {
    // 决定处理哪些参数,如果返回true,就是这个类型的参数需要被处理
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
    	// 判断参数上有没有UserPhone这个注解,如果有,返回true,同时调用resolveArgument为参数赋值
        return parameter.getParameterAnnotation(UserPhone.class)!=null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		// 编码,获取phone的值
        String phone = ""
        return phone;
    }
}

3.使用场景

  • 在参数名前加注解,即可完成自动注入参数值
	@GetMapping("/{id}")
    public RespResult queryByCondition(@PathVariable("id") Long id, @UserPhone String phone){
		xxxService.queryByCondition(id, phone);
		// return语句
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值