SpringBoot项目中逆向Protocol Buffer生成的Java文件并添加字段
解决Protocol Buffer生成类的修改问题
作为SpringBoot新手加入项目后,遇到了需要修改Protocol Buffer自动生成的Java类的问题:看到MyAttributesOuterClass类(由protoc生成,标注来源为my_attributes.proto),想要添加新字段,但找不到对应的.proto源文件。项目中已配置Protobuf相关依赖与Maven插件,以下是解决方法:
一、查找my_attributes.proto文件的来源
- 检查项目目录:
.proto文件通常默认存放在src/main/proto或src/main/resources/proto目录,也可能存在于项目子模块的对应路径下,需遍历所有模块排查 - 检查依赖来源:打开生成的
MyAttributesOuterClass类,查看其文件路径。如果路径指向本地Maven仓库(如~/.m2/repository下的jar包),说明该类来自第三方依赖,需联系团队找到对应的依赖项目获取.proto文件 - 查看插件配置:从Maven插件的
<configuration>节点中,检查是否通过<protoSourceRoot>自定义了.proto文件的存放路径,默认路径为src/main/proto
二、逆向工程从Java类生成.proto文件
如果确实无法找到原始.proto文件,可以通过以下步骤逆向生成:
- 安装与项目中
protobuf.version一致的protoc编译器(比如项目用的是3.25.1,就下载对应版本) - 使用Protobuf逆向工具(专门用于将生成的Java类反编译为
.proto定义的工具)解析目标类,解析时需保留原有字段的编号、类型与注释,确保后续生成的类与原有版本兼容 - 验证逆向生成的
.proto文件:通过protoc编译该文件,对比生成的Java类与原类是否一致,确认无误后再进行修改
三、添加新字段的正确流程
- 修改
.proto文件:按照Protobuf语法添加新字段,注意不要修改现有字段的编号,给新字段分配未使用的唯一编号;若需废弃旧字段,可添加[deprecated = true]标记,不要直接删除旧字段,保证兼容性 - 重新生成Java类:执行Maven命令触发Protobuf编译插件,重新生成对应的Java类:
mvn protobuf:compile protobuf:compile-custom - 验证与使用:检查新生成的Java类是否包含新增字段,之后即可在项目代码中使用该字段
生成的Java类片段
package org.thingsboard.server.controller.tts;// Generated by the protocol buffer compiler. DO NOT EDIT! // source: my_attributes.proto // Protobuf Java Version: 3.25.1 public final class MyAttributesOuterClass { private MyAttributesOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } /** * <pre> * Enum of device types * </pre> * * Protobuf enum {@code DeviceType} */ …
Maven依赖片段
<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> </dependency> ... <plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> </plugin>
根目录pom.xml插件完整配置
<plugin> <groupId>org.xolstice.maven.plugins</groupId> <artifactId>protobuf-maven-plugin</artifactId> <version>0.6.1</version> <configuration> <!-- The version of protoc must match protobuf-java. If you don't depend on protobuf-java directly, you will be transitively depending on the protobuf-java version that grpc depends on. --> <protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier} </protocArtifact> <pluginId>grpc-java</pluginId> <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier} </pluginArtifact> </configuration> <executions> <execution> <goals> <goal>compile</goal> <goal>compile-custom</goal> <goal>test-compile</goal> </goals> </execution> </executions> </plugin>
内容的提问来源于stack exchange,提问作者ERTY
相关产品推荐
相关产品推荐

