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

Spring Boot中RestDocumentationGenerationException报错求助:文件无法写入根目录

解决Spring REST Docs MockMvc在M2 Mac上输出目录权限问题

在M2处理器的MacBook Pro上使用Spring REST Docs MockMvc生成API文档时,遇到根目录/只读的权限错误,尽管已设置系统属性org.springframework.restdocs.outputDir为正确路径,但调试发现RestDocumentationContextProvider的outputDirectory为null,仅在valuesStore中存在target/generated-snippets的路径配置。

解决方案

1. 确保系统属性传递到测试进程

系统属性需要正确传递给测试JVM,否则Spring REST Docs无法读取:

  • Maven用户:在pom.xml的maven-surefire-plugin中配置系统属性:
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
            <systemPropertyVariables>
                <org.springframework.restdocs.outputDir>${project.build.directory}/generated-snippets</org.springframework.restdocs.outputDir>
            </systemPropertyVariables>
        </configuration>
    </plugin>
    
  • Gradle用户:在build.gradle的test任务中添加系统属性:
    test {
        systemProperty 'org.springframework.restdocs.outputDir', "${buildDir}/generated-snippets"
    }
    
  • IDE直接运行测试:在测试运行配置中手动添加系统属性org.springframework.restdocs.outputDir,值为你的项目target/generated-snippets绝对路径。

2. 显式配置输出目录(推荐)

跳过系统属性依赖,直接在测试代码中显式指定输出目录,避免环境传递问题:
修改setUp方法,给DocumentationConfiguration添加输出目录配置:

@BeforeEach
public void setUp(RestDocumentationContextProvider restDocumentation) {
    this.mvc = MockMvcBuilders.webAppContextSetup(this.context)
          .apply(MockMvcRestDocumentation.documentationConfiguration(restDocumentation)
              // 可选:配置URI信息
              .uris()
              .withScheme("http")
              .withHost("localhost")
              .withPort(8080)
              .and()
              // 显式设置输出目录
              .snippets()
              .withOutputDirectory(new File("/Users/me/workspace/my-service/target/generated-snippets")))
          .build();
}

如果不想硬编码路径,可以用项目根目录相对路径:

.withOutputDirectory(new File(System.getProperty("user.dir") + "/target/generated-snippets"))

3. 检查版本兼容性

确保Spring REST Docs版本与Spring Boot版本匹配:

  • Spring Boot 3.x 对应 Spring REST Docs 3.x
  • Spring Boot 2.x 对应 Spring REST Docs 2.x
    版本不兼容可能导致配置逻辑异常,出现输出目录读取失败的情况。

问题原因

当outputDirectory为null时,Spring REST Docs会尝试使用默认路径(根目录/)作为 fallback,而M2 Mac的根目录是只读状态,因此触发权限错误。系统属性未被测试进程读取,是导致outputDirectory为null的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:35:26