WebArgumentResolver 自定义参数解析案例

WebArgumentResolver 用于定义自定义的参数解析逻辑,用于将传入的 Web 请求参数或模型中的属性注入到控制器方法的参数中。

业务场景:

假设你正在开发一个 Web 应用程序,该程序需要处理一些复杂的数据结构,这些结构并不适合直接从标准的请求参数中获取,或者你需要从多个来源(如请求头、请求体、会话等)获取参数。

1. 创建自定义参数解析器:

java 复制代码
import org.springframework.web.method.support.WebArgumentResolver;
import org.springframework.web.bind.annotation.PathVariable;

public class CustomArgumentResolver implements WebArgumentResolver {

    @Override
    public Object resolveArgument(MethodParameter parameter, NativeWebRequest webRequest) throws Exception {
        if (parameter.hasParameterAnnotation(PathVariable.class)) {
            // 从 URL 路径变量中获取参数值
            String name = parameter.getParameterAnnotation(PathVariable.class).value();
            return webRequest.getAttribute(name, 0);
        }
        // 可以添加更多的参数解析逻辑
        return WebArgumentResolver.UNRESOLVED;
    }
}

2. 注册自定义参数解析器:

java 复制代码
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(new CustomArgumentResolver());
    }
}

3. 使用自定义参数解析器:

java 复制代码
@GetMapping("/users/{userId}/profile")
public String getUserProfile(@PathVariable("userId") Long userId, CustomType customType) {
    // 使用 userId 和 customType 中的数据
    return "userProfile";
}

在这个例子中,CustomArgumentResolver 会尝试解析带有 @PathVariable 注解的参数。如果参数是自定义类型 CustomType,它将从请求中获取所需的数据并注入到控制器方法中。

总结

  • WebArgumentResolver 允许开发者自定义参数的解析逻辑,提供更大的灵活性。
  • 它可以用于处理复杂的数据结构,或者从非标准来源获取参数。
  • 使用 WebArgumentResolver 可以提高应用程序的模块化和可维护性,尤其是当涉及到复杂的参数处理时。
相关推荐
别动我齐刘海1 分钟前
C++ 工程化学习
java·linux·前端·c++·学习·机器学习·机器人
码事漫谈2 分钟前
你让AI干的活,它可能只干了十分之一——而你根本看不出来
后端
Wx-bishekaifayuan18 分钟前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游
loulanyue_23 分钟前
从个人提效到团队可验证交付:中宏保险AI Coding流水线重塑与Qoder实战——读中宏保险AI架构总监王志宇2026云栖专场演讲
人工智能·架构
Wx-bishekaifayuan1 小时前
springboot汉中旅游服务平台41442-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
code2cat1 小时前
Java进阶篇之AtomicLongFieldUpdater:把累计额度留在对象字段中
java·cas·并发编程
WeiXin_DZbishe1 小时前
基于springboot城市公交实时运营与调度系统-计算机毕设 附源码【课程设计】66173
java·vue.js·spring boot·后端·python·php·课程设计
泡茶喝茶写代码1 小时前
A股量化数据工程:从 REST 接口到策略信号(第 18 篇):放量缩量异动扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
WeiXin_DZbishe2 小时前
基于Springboot+AI的kuall音乐广场的设计与实现-计算机毕设 附源码【课程设计】12715
vue.js·人工智能·spring boot·后端·python·php·课程设计