【问题标题】:How to use google protobuf compiler with maven-compiler-plugin如何使用带有 maven-compiler-plugin 的 google protobuf 编译器
【发布时间】:2021-05-17 22:33:39
【问题描述】:

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

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

  generateProtoTasks.generatedFilesBaseDir = generatedProtoPath
}

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

【问题讨论】:

    标签: java maven gradle protocol-buffers


    【解决方案1】:

    回答我自己的问题以便有人觉得它有帮助:
    谷歌 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>
    

    这是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));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-18
      • 2018-11-25
      • 2021-02-07
      • 2014-10-04
      • 2020-05-16
      • 2020-12-22
      • 2013-01-14
      • 2012-12-19
      相关资源
      最近更新 更多