配置 Maven 从 Protobuf 生成 Java 代码
时间: 2024-03-02 09:50:50 浏览: 125
要配置 Maven 从 Protobuf 生成 Java 代码,需要完成以下步骤:
1.在 pom.xml 文件中添加 protobuf 插件:
```
<build>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocExecutable>protoc</protocExecutable>
<pluginId>grpc-java</pluginId>
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:1.36.0:exe:${os.detected.classifier}
</pluginArtifact>
<outputDirectory>${project.build.directory}/generated-sources/protobuf/java</outputDirectory>
<clearOutputDirectory>false</clearOutputDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
2.在 dependencies 中添加 protobuf 相关依赖:
```
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.36.0</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.36.0</version>
</dependency>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.11.4</version>
</dependency>
</dependencies>
```
3.配置完毕后,在 Maven 中执行以下命令生成 Java 代码:
```
mvn protobuf:compile
```
生成的 Java 代码将会在 `target/generated-sources/protobuf/java` 目录下。
阅读全文