如何使用 google protobuf 编译器和 maven-compiler-plugin

voi*_*urn 11 java protocol-buffers gradle maven

我有一个简单的java项目(没有spring),并且在src/resources文件夹中有一个protobuf文件test.proto,我想从中生成源代码。我在几个 地方读到,要使用该插件,我需要先在本地安装它。但在我之前的 gradle 项目中,我不需要做这样的事情,只需像下面这样的简单配置即可适用于 gradle :

protobuf {
  protoc {
    artifact = 'com.google.protobuf:protoc:3.8.0'
  }

  generateProtoTasks.generatedFilesBaseDir = generatedProtoPath
}
Run Code Online (Sandbox Code Playgroud)

如果我想使用 google 提供的protoc编译器并生成代码而不在我的生产机器上下载和安装任何东西,那么 Maven 中有什么类似的事情呢?

voi*_*urn 22

要回答我自己的问题,以便有人发现它有帮助:
google protobuf 3.7.0:Maven 更改 - 将其添加到您的 pom.xml 中:

<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java</artifactId>
    <version>3.7.0</version>
</dependency>
<dependency>
    <groupId>com.google.protobuf</groupId>
    <artifactId>protobuf-java-util</artifactId>
    <version>3.7.0</version>
</dependency>
</dependencies>
<build>
    <extensions>
        <extension>
            <groupId>kr.motd.maven</groupId>
            <artifactId>os-maven-plugin</artifactId>
            <version>1.6.0</version>
        </extension>
    </extensions>
    <plugins>
    <plugin>
        <groupId>org.xolstice.maven.plugins</groupId>
        <artifactId>protobuf-maven-plugin</artifactId>
        <version>0.6.1</version>
        <extensions>true</extensions>
        <executions>
            <execution>
                <goals>
                    <goal>compile</goal>
                    <goal>test-compile</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <additionalProtoPathElements>
                <additionalProtoPathElement>${project.basedir}/src/main/resources</additionalProtoPathElement>
            </additionalProtoPathElements>
            <protocArtifact>com.google.protobuf:protoc:3.7.0:exe:${os.detected.classifier}</protocArtifact>
        </configuration>
    </plugin>
Run Code Online (Sandbox Code Playgroud)

这是java类:

public class ProtobufTrial {
  public static void main(String[] args) throws Exception {
    String jsonString = "";
    MyProto.MyEventMsg.Builder builder = MyProto.MyEventMsg.newBuilder();
    JsonFormat.parser().ignoringUnknownFields().merge(jsonString, builder);
    MyProto.MyEventMsg value = builder.build();

    // This is for printing the proto in string format
    System.out.println(JsonFormat.printer().print(value));
  }
}
Run Code Online (Sandbox Code Playgroud)