You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@ParameterObject时如何让请求参数名与类字段名不同?

实现@ParameterObject参数名与类字段名不一致的方案

你可以通过以下两种方式实现请求参数下划线格式、类字段驼峰格式的绑定需求:

一、字段级注解指定映射关系

在SearchParams类的字段上添加@JsonProperty注解,直接声明对应的下划线参数名,无需修改类字段或方法名:

import com.fasterxml.jackson.annotation.JsonProperty;

public class SearchParams {

    @JsonProperty("some_param")
    private String someParam;

    @JsonProperty("some_other_param")
    private String someOtherParam;

    // 需提供标准的getter/setter方法,Spring MVC依赖JavaBean规范完成参数绑定
    public String getSomeParam() {
        return someParam;
    }

    public void setSomeParam(String someParam) {
        this.someParam = someParam;
    }

    public String getSomeOtherParam() {
        return someOtherParam;
    }

    public void setSomeOtherParam(String someOtherParam) {
        this.someOtherParam = someOtherParam;
    }
}

配置完成后,请求GET /foos?some_param=abc&some_other_param=xyz时,参数会自动绑定到someParam和someOtherParam字段。

二、全局配置实现自动驼峰转下划线

如果有多个参数对象需要统一处理,可通过全局配置让Spring自动将下划线格式的请求参数映射到驼峰命名的类字段:

Spring Boot 配置文件方式

在application.properties中添加配置:

# 启用驼峰与下划线的自动转换
spring.jackson.property-naming-strategy=SNAKE_CASE

或application.yml:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE

代码配置方式

创建Jackson配置类,指定全局命名策略:

import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonNamingConfig {
    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
    }
}

全局配置生效后,所有使用@ParameterObject的类都能自动将下划线参数绑定到驼峰字段,无需逐个字段添加注解。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:37:30