Springboot 之 自定义方法多参数解析器

因为自己有一个业务,需要判断用户的邮箱和手机号存在不存在,几乎每个接口都有。但是每个接口可能是邮箱可能是手机号.所以准备用注解实现
另外,我这里多加了一个用户类型,可以多参数设置
参考文章 : Springboot 之 自定义方法参数解析器

1. 参数枚举

public enum XkjParamEnum {

	USER,

    EMAIL,

    PHONE,

}

2. 自定义注解

import cn.newsalary.xkj.perm.biz.enums.XkjParamEnum;

import java.lang.annotation.*;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface XkjParam {

    XkjParamEnum type();

    /**
     * @see https://github.com/alibaba/fastjson/wiki/JSONPath
     */
    String value() default "";
}

3. 自定义方法参数解析器实现

@Component
public class XkjParamResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(XkjParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {

        //获取参数类类型
        Class paramObjClass = parameter.getParameterType();
        //根据class new 出对象
        Object paramObj = paramObjClass.newInstance();

		// 获取用户token
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("Access-Token");
        if (StringUtils.isBlank(token)) {
        	// 返回错误信息
            throw new CommonException(CommonError.MISSING_TOKEN);
        }

        XkjParamEnum type = parameter.getParameterAnnotation(XkjParam.class).type();

        if (type == null) {
        	// 返回错误信息
            throw new CommonException(BizError.XKJPARAM_MISSING);
        }

        // 是否需要判断字符串为空
        Boolean isJudgeStringBank = false;

        switch (type) {
            case USER:
            	// 这里判断接收类型,如果他的注解是User,但是写成了String,就不返回信息
                if (parameter.getParameterType().equals(User.class)) {
                    // 获取用户信息
                    paramObj = ;
                }
                break;
            case EMAIL:
                if (parameter.getParameterType().equals(String.class)) {
                    // 获取用户邮箱信息
                    paramObj = ;
                    isJudgeStringBank = true;
                }
                break;
            case PHONE:
                if (parameter.getParameterType().equals(String.class)) {
                    // 获取手机信息
                    paramObj = ;
                    isJudgeStringBank = true;
                }
                break;
        }

        if (paramObj == null) {
            // 返回错误信息
            throw new CommonException(BizError.NO_MANAGER_COMPANY);
        }
        if (isJudgeStringBank) {
            if (paramObj == "") {
                // 返回错误信息
                throw new CommonException(BizError.NO_MANAGER_COMPANY);
            }
        }

        return paramObj;
    }
    
}

4. 将自定义的参数解析器配置到spring容器中

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {
    @Resource
    private XkjParamResolver xkjParamResolver ;

    @Override
    protected void addArgumentResolvers(List argumentResolvers) {
        argumentResolvers.add(xkjParamResolver);
        // 注册Spring data jpa pageable的参数分解器
        argumentResolvers.add(new PageableHandlerMethodArgumentResolver());
    }

    // swagger2 访问
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

5. controller中使用

    public Object getUser(@XkjParam(type = XkjParamEnum.USER) User user) {
        System.out.println(user);
        return new RtnResult<>(user);
    }

	public Object getUserPhone(@XkjParam(type = XkjParamEnum.PHONE) String phone) {
        System.out.println(phone);
        return new RtnResult<>(phone);
    }
    
	public Object getUserEmail(@XkjParam(type = XkjParamEnum.EMAIL) String email) {
        System.out.println(email);
        return new RtnResult<>(email);
    }

	// 这个是错误演示,比方说我枚举是 EMAIL , 但是参数却是 User, 因为在后面判断过,所以这里是空的值。或者你也可以选择报错
	public Object getError(@XkjParam(type = XkjParamEnum.EMAIL) User user) {
        System.out.println(email);
        return new RtnResult<>(email);
    }

你可能感兴趣的:(Java,Sring,Boot,注解,自定义注解)