You need to enable JavaScript to run this app. 如何创建Spring Boot自定义注解实现PathVariable/RequestParam字符串转Long
优惠活动
大模型
产品
解决方案
定价
更多

如何创建Spring Boot自定义注解实现PathVariable/RequestParam字符串转Long

实现方案说明

这个需求完全可以落地,不需要强制把参数绑定到自定义对象上,通过Spring MVC的参数解析扩展机制,就能实现“只有标注@ChangeFromStringToLong注解的参数,才会走混淆字符串转Long的逻辑”,且完全不干扰Spring默认的参数解析规则。

注意避坑:不要直接注册全局String -> Long类型的Converter,否则会覆盖Spring默认的数字字符串转Long的逻辑——所有场景下的字符串到Long的转换都会走你的解密算法,比如正常传入的数字格式参数"123"也会被错误处理。

具体实现步骤

1. 定义目标注解

首先创建用来标记需要走转换逻辑的注解,用来精准匹配需要处理的参数:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ChangeFromStringToLong {
}

2. 实现带注解感知的参数解析器

自定义参数解析器,只处理同时满足以下条件的参数:

  • 标注了@ChangeFromStringToLong注解
  • 参数类型为long基本类型或Long包装类型
  • 来源为PathVariable或RequestParam

解析器的核心逻辑是拿到原始的字符串值(比如路径里的"Ao93Fbs"),调用你已有的混淆解密算法转成Long后,直接作为方法入参返回。
示例代码:

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.bind.support.WebDataBinderFactory;

import java.util.Map;

public class DecodedLongArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        boolean hasCustomAnno = parameter.hasParameterAnnotation(ChangeFromStringToLong.class);
        boolean isLongType = parameter.getParameterType().equals(long.class) 
                || parameter.getParameterType().equals(Long.class);
        boolean hasPathVariable = parameter.hasParameterAnnotation(PathVariable.class);
        boolean hasRequestParam = parameter.hasParameterAnnotation(RequestParam.class);
        // 仅匹配带自定义注解的Long类参数,且来源为路径变量或请求参数
        return hasCustomAnno && isLongType && (hasPathVariable || hasRequestParam);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                   NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String rawStringValue = null;
        // 从路径变量中获取原始字符串值
        PathVariable pathAnno = parameter.getParameterAnnotation(PathVariable.class);
        if (pathAnno != null) {
            Map<String, String> pathVariables = (Map<String, String>) webRequest.getAttribute(
                    HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
            rawStringValue = pathVariables.get(pathAnno.value());
        }
        // 从请求参数中获取原始字符串值
        RequestParam requestAnno = parameter.getParameterAnnotation(RequestParam.class);
        if (requestAnno != null) {
            rawStringValue = webRequest.getParameter(requestAnno.value());
        }
        // 空值直接返回
        if (rawStringValue == null || rawStringValue.isBlank()) {
            return null;
        }
        // 替换为你自己的混淆字符串解密转Long的逻辑
        return decodeObfuscatedId(rawStringValue);
    }

    private Long decodeObfuscatedId(String obfuscatedStr) {
        // 这里接入你之前写的base62解码、ID混淆映射等逻辑
        // 示例为占位实现
        return Math.abs(obfuscatedStr.hashCode() * 123456L);
    }
}

3. 注册自定义解析器

把写好的参数解析器注册到Spring MVC的配置链路中,加在默认解析器的最前面,保证能优先匹配带自定义注解的参数:

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;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(0, new DecodedLongArgumentResolver());
    }
}

实现效果

完成配置后,你最开始写的接口代码可以直接正常运行,不需要任何额外调整:

@RequestMapping(path = "/{accountID}", method = RequestMethod.GET)
public Object testFunction(@ChangeFromStringToLong @PathVariable("accountID") long accountID) {
    // 这里的accountID已经是解密后的Long类型值,可以直接使用
    return accountID;
}

方案优势

  • 逻辑隔离:只有明确标注@ChangeFromStringToLong的参数才会走解密转换逻辑,完全不会影响其他接口的默认参数解析
  • 贴合使用习惯:不需要把参数封装到自定义对象里,直接用long/Long基本类型接收,和你预期的写法完全一致
  • 灵活兼容:同一个解析器可以同时支持PathVariable和RequestParam两类参数的转换,不需要重复实现逻辑

内容的提问来源于stack exchange,提问作者Damian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 14:45:08