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

OpenRewrite未更新generated-sources目录下Java类问题求助

解决OpenRewrite无法修改target/generated-sources下生成类的问题

你怀疑的源码生成在Rewrite修改后执行导致覆盖是最可能的原因,除此之外还有几个常见问题可以排查:

可能的原因及解决步骤

1. Maven插件执行顺序颠倒

代码生成插件(如MyBatis Generator、JAXB2插件等)默认绑定generate-sources阶段,而如果OpenRewrite的执行时机早于这个阶段,或者你手动执行rewrite:run后又触发了代码生成,就会导致修改被覆盖。

解决方法:

  • 把OpenRewrite插件绑定到process-sources阶段(该阶段在generate-sources之后执行),确保代码生成完成后再执行Rewrite修改。示例POM配置:
    <plugin>
        <groupId>org.openrewrite.maven</groupId>
        <artifactId>rewrite-maven-plugin</artifactId>
        <version>4.45.0</version>
        <executions>
            <execution>
                <id>rewrite-generated-classes</id>
                <phase>process-sources</phase>
                <goals>
                    <goal>run</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <activeRecipes>
                <!-- 替换为你移除注解的自定义Recipe -->
                <recipe>com.yourteam.RemoveTargetAnnotations</recipe>
            </activeRecipes>
            <includes>
                <include>src/main/java/**/*.java</include>
                <!-- 显式包含生成源码目录 -->
                <include>target/generated-sources/**/*.java</include>
            </includes>
        </configuration>
    </plugin>
    

2. OpenRewrite未显式包含生成目录

即使通过build-helper-maven-plugin把target/generated-sources设为源码目录,OpenRewrite默认的扫描范围可能只覆盖src/下的文件,需要显式指定包含该目录。

解决方法:
在Rewrite插件的<configuration>里添加<includes>节点,把target/generated-sources/**/*.java加入扫描范围,如上例所示。

3. 生成的类文件是只读状态

部分代码生成工具会自动把生成的文件设为只读,导致OpenRewrite无法修改。

解决方法:

  • 手动检查target/generated-sources下的文件权限,确认是否可编辑。
  • 调整代码生成工具的配置,关闭只读设置。比如MyBatis Generator可以添加:
    <generatedFileOptions>
        <readonly>false</readonly>
    </generatedFileOptions>
    

4. Rewrite规则未匹配到目标注解

如果你的移除注解规则写得不够精准,可能无法命中生成类里的注解(比如注解全类名写错、未考虑注解参数等)。

解决方法:

  • 查看rewrite:dryRun的详细输出,确认生成类是否被规则匹配。
  • 调整规则的匹配条件,比如使用注解的全限定类名,或者放宽匹配范围(如果需要移除所有注解)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:33:25