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

使用Spring Rest-Docs注入多角色属性失败:仅显单个角色且报Mustache异常

解决Spring Rest Docs多授权角色显示异常问题

问题根源

你传递角色时误用了单个值而非集合类型,同时Mustache模板未正确遍历集合,导致仅显示最后一个角色并抛出找不到role字段的异常。

正确实现步骤

  1. 传递集合类型的角色属性
    在构建requestHeader文档时,确保roles属性的值是集合(List或数组),而非单个字符串:

    import java.util.Arrays;
    import static org.springframework.restdocs.request.RequestDocumentation.headerWithName;
    import static org.springframework.restdocs.snippet.Attributes.key;
    
    // 文档构建代码示例
    this.mockMvc.perform(get("/your-api-path")
            .header("Authorization", "Bearer token"))
        .andDo(document("your-api-id",
            requestHeaders(
                headerWithName("Authorization").description("JWT 授权令牌"),
                attributes(key("roles").value(Arrays.asList("Smart User", "Admin")))
            )
        ));
    
  2. 修改Mustache模板遍历集合
    找到对应的requestHeader模板文件(通常在src/main/resources/org/springframework/restdocs/templates/request-headers.snippet),添加遍历角色集合的代码:

    {{#tableCellContent}}
    <h4>请求头</h4>
    {{> request-headers-table}}
    
    {{#roles}}
    <h4>授权角色</h4>
    <ul>
        {{#roles}}
        <li>{{.}}</li>
        {{/roles}}
    </ul>
    {{/roles}}
    {{/tableCellContent}}
    

    说明:

    • {{#roles}}是Mustache的区块标签,用于触发集合遍历
    • {{.}}表示当前遍历到的集合元素值,会依次输出每个角色
  3. 关键注意事项

    • 代码中attributes的键roles必须和模板中的区块标签{{#roles}}完全一致
    • 禁止将多个角色用逗号拼接成单个字符串传递,必须用集合类型让模板支持遍历
    • 模板中若使用单数{{role}},会因找不到对应字段抛出异常,需改为集合遍历的写法

内容的提问来源于stack exchange,提问作者Arc-E-Tect

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 01:57:14