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 可以提高应用程序的模块化和可维护性,尤其是当涉及到复杂的参数处理时。
相关推荐
Tutankaaa10 分钟前
从10队到50队:知识竞赛软件的高并发场景如何设计?
java·经验分享·后端·spring
下次再写22 分钟前
微服务架构实战:Spring Boot + Spring Cloud 从入门到精通
java·spring boot·spring cloud·微服务架构·服务注册与发现·分布式系统·api网关
bang冰冰27 分钟前
Trae工具安装和使用教程(新手零基础入门,全程无坑)
java·人工智能·python
阿丰资源28 分钟前
基于Spring Boot的网上摄影工作室系统(源码一键运行)
java·spring boot·后端
AI玫瑰助手29 分钟前
Agent架构:规划、记忆、工具、反思
人工智能·架构·agent
阿维的博客日记38 分钟前
容器是怎么管理 Bean 的?
java·bean
hedian1161 小时前
2026短剧系统技术选型:H5私有化部署的技术架构与实践
架构
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第40题:Java中的深拷贝和浅拷贝有什么区别
java·开发语言·后端·面试
@小匠1 小时前
云之家表单数据解析 skills (yzj-form-parser)
java
云烟成雨TD1 小时前
Spring AI Alibaba 1.x 系列【48】状态图编译配置类:CompileConfig 源码解析
java·人工智能·spring