大家好,我是程序员柏风,AI 最全的 Vibecoding 学习地图 http://coderoadmap.cn 作者。
代码生成
protoc 编译 .proto 生成 Java message 类与 gRPC stub/skeleton。Maven/Gradle 插件可在 compile 阶段自动执行,避免手写序列化代码。
学习目标
- 配置
protobuf-maven-plugin(或 Gradle equivalent) - 理解
*Grpc类、TrackServiceGrpc.TrackServiceImplBase职责 - 在 lab 模块生成代码,不替换现有 REST Controller
核心内容
Maven 插件片段
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.25.3:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.64.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals><goal>compile</goal><goal>compile-custom</goal></goals>
</execution>
</executions>
</plugin>
依赖:grpc-netty-shaded、grpc-protobuf、grpc-stub;Java 9+ 需 javax.annotation-api。
生成物一览
| 文件 | 用途 |
|---|---|
Track.java | message POJO + Builder |
TrackServiceGrpc.java | newStub / newBlockingStub / bindService |
TrackServiceImplBase | 服务端继承并实现 RPC 方法 |
mvn generate-sources
# target/generated-sources/protobuf/...
生成代码 勿手改;改契约只改 .proto 再编译。与 spring-boot-essentials 中 MapStruct/DTO 思路类似——generated vs hand-written 分层。
lab 模块布局建议
platform-api/ ← REST TrackController(生产)
platform-grpc-lab/ ← proto + gRPC server(profile lab-grpc)
graphql-essentials 实验也是 独立 profile;gRPC 同理,避免污染默认 8080 REST 行为。
练习
- 执行
mvn compile,在target/找到TrackServiceGrpc - 修改
.proto增字段,观察编译报错如何提示 field number - 在
.gitignore确认是否忽略target/(生成物不入库)
小结
protoc 把 .proto 变成类型安全的 Java API。 下一课实现 TrackServiceImplBase 启动 gRPC Server。