Maven根据Google proto文件自动生成java对象
引言
在分布式系统开发中,Google Protocol Buffers(简称Protobuf)凭借其高效序列化能力和跨语言兼容性,已成为微服务通信、数据存储等场景的首选协议格式。本文将以Maven为核心工具链,详解如何通过.proto
文件自动生成Java对象,并实现与Spring Boot项目的深度集成。
一、Maven插件配置
推荐使用protobuf-maven-plugin
插件
- 自动化编译:通过
protoc
编译器将.proto
文件生成Java代码 - 多平台支持:通过
os-maven-plugin
自动识别操作系统架构(Windows/Linux/macOS) - 版本管理:支持Protobuf 3.x及gRPC扩展
<plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>0.6.1</version><configuration><protoSourceRoot>./proto</protoSourceRoot><includes><include>**/spec/**</include></includes></configuration></plugin>
其中,protoSourceRoot是存放proto文件的相对路径地址,include是在相对路径下更小的文件包范围限制。准比的proto文件如下:
syntax = "proto3";
package org.spec.extend;
option java_package = "org.spec.extend";
message Bin{float left_bound = 1;float right_bound = 2;float filling_value = 4;
}message VariableBins{string feature_name = 1;string feature_type = 2;repeated Bin valid_bins = 5;bool is_woe = 6;
}message Bins{repeated VariableBins variable_bins = 1;string model_hash = 2;
}
二、代码生成
在Maven pom下,执行插件的compile,会自动生成对应的java文件。
三、项目集成
项目完整pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.springboot.test</groupId><artifactId>pb2java</artifactId><version>1.0-SNAPSHOT</version><packaging>jar</packaging><name>pb2java</name><url>http://maven.apache.org</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.25.5</version></dependency><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java-util</artifactId><version>3.25.5</version></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-netty-shaded</artifactId><version>1.62.2</version></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-protobuf</artifactId><version>1.62.2</version></dependency><dependency><groupId>io.grpc</groupId><artifactId>grpc-stub</artifactId><version>1.62.2</version></dependency></dependencies><build><plugins><plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>0.6.1</version><configuration><protoSourceRoot>./proto</protoSourceRoot><includes><include>**/spec/**</include></includes></configuration></plugin></plugins></build>
</project>
测试代码:
public static void main( String[] args ) throws InvalidProtocolBufferException {BinData.Bin bin = BinData.Bin.newBuilder().setLeftBound(2.0F).setRightBound(4.9F).setFillingValue(0.1F).build();System.out.println(JsonFormat.printer().print(bin));}