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 可以提高应用程序的模块化和可维护性,尤其是当涉及到复杂的参数处理时。
相关推荐
Decay__4 分钟前
12_MySQL InnoDB 内存与锁调优 —— Buffer Pool、redo log、隔离级别与锁等待
运维·数据库·sql·mysql·架构
Wang's Blog1 小时前
Java 项目实战: 交友项目 - FastDFS:入门案例
java·开发语言·交友
一只爱撸猫的程序猿1 小时前
我看着一个 AI 引擎在 14 天里,从"记忆"走进了"搜索"
人工智能·后端·架构
apcipot_rain2 小时前
C++转Java日记(03)
java·开发语言·c++
皮皮林5512 小时前
Java实现微信扫码登录
java
陈随易4 小时前
纯 Go 写的 JS 引擎,跑分超过了 C 语言的 QuickJS
前端·后端·程序员
Yyyyyy~4 小时前
【Java】Day4Web基础知识
java·spring boot
卷无止境4 小时前
RAGFlow 项目全景报告:从文档解析引擎到 Agent 原生数据库
后端·python
小Z先生5 小时前
我用 Go + 系统 WebView 写了个纯本地 Postman:不装 Electron、不连云端
后端·github
IT_陈寒5 小时前
Redis连接池泄漏那次,我差点把生产环境搞崩了
前端·人工智能·后端