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

SpringGraphQL中非空对象/数组参数解析为null导致内部错误问题

解决方案

1. 修复自定义输入类的映射与JavaBean规范

GraphQL Schema定义的输入类型为MyArr,但Java类命名为MyArray,名称不匹配会导致Spring GraphQL无法正确关联参数。同时,自定义输入类需满足JavaBean绑定要求:

import org.springframework.graphql.data.method.annotation.InputMapping;

// 显式关联GraphQL中的输入类型名称
@InputMapping(name = "MyArr")
public class MyArray {
    private String[] arr;

    // 提供无参构造器,用于Spring参数绑定
    public MyArray() {}

    // 可选带参构造,用于手动实例化
    public MyArray(String[] arr) {
        this.arr = arr;
    }

    public String[] getArr() {
        return arr;
    }

    // 添加setter方法,Spring通过setter注入字段值
    public void setArr(String[] arr) {
        this.arr = arr;
    }
}

2. 对齐Resolver参数与Schema命名

在@Argument注解中显式指定参数名(对应Schema中的args),避免隐式匹配失败:

@Controller
public class RecipesGraphQLController {

    @QueryMapping
    public String testQuery(@Argument(name = "args") MyArray arr) {
        return arr.getArr()[0];
    }
}

3. 直接使用字符串数组参数的修复

若直接使用字符串数组作为参数,需确保Schema与Java类型匹配,并显式指定参数名:

Schema修改:

type Query{
  testQuery(args: [String!]!): String!
}

Resolver代码:

@QueryMapping
public String testQuery(@Argument(name = "args") String[] arr) {
    return arr[0];
}
排查方向
  • 版本升级验证:当前使用的Spring 3.0.5 + Spring GraphQL 1.1.2存在复杂类型/数组参数绑定的已知bug,升级到Spring GraphQL 1.2.0+或Spring 3.1.x版本可解决该问题。
  • 开启绑定日志:添加日志配置查看参数绑定细节:
    logging.level.org.springframework.graphql=DEBUG
    logging.level.org.springframework.web=DEBUG
    
    重点关注日志中是否有类型不匹配、映射未找到等绑定失败提示。
  • JavaBean规范检查:自定义输入类必须提供无参构造器及对应setter方法(或使用@ConstructorBinding配合@InputMapping实现构造器注入)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 15:35:14