maven-protobuf-plugin 编译多个protobuf文件 出现is already defined in,不用替换类名或更改嵌套结构

背景

使用maven的protobuf插件可以在maven compile阶段自动编译protobuf文件,替换手动执行protoc命令编译产生java代码,然后再拷贝替换等这种原始方法。
搜索protobuf插件后,发现当前这个版本的热度较高,官网链接

<plugin>
    <groupId>org.xolstice.maven.plugins</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.5.1</version>
</plugin>

问题

配置好后编译发现出现 XXX is already defined in XXX 的错误,具体错误参考这个博客类似的issue
为了解决这个问题,大致有两个办法:

  • 更改重名的message
  • 使用嵌套结构

这两个办法,都会使得编译后的类产生结构变化,导致还要更改其他代码,pass

解决

仔细看了下这个issue,从这段话可以看出来,这个人之前用的maven插件不会产生这个问题

尝试了插件的老版本,发现依然产生这个问题,后来在这个插件github仓库中发现它fork自另一个项目,github,这个项目的maven插件版本为

<plugin>
    <groupId>com.github.igor-petruk.protobuf</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.5</version>
</plugin>

在使用了这个插件后,即使protobuf目录中有多个protobuf文件,也不会有问题了。具体的配置如下,这样在mvn compile编译源代码前,会先编译protobuf文件产生.java代码。

<plugin>
    <groupId>com.github.igor-petruk.protobuf</groupId>
    <artifactId>protobuf-maven-plugin</artifactId>
    <version>0.6.5</version>
    <configuration>
        <!--默认是protoc,即/usr/bin/local/protoc-->
        <protocCommand>${project.basedir}/protoc</protocCommand>
        <!--inputDirectories,默认src/main/protobuf-->
        <outputDirectory>${project.basedir}/src/main/java</outputDirectory>
        <cleanOutputFolder>false</cleanOutputFolder>
    </configuration>
    <executions>
        <execution>
            <phase>process-sources</phase>
            <goals>
                <goal>run</goal>
            </goals>
        </execution>
    </executions>
</plugin>
原文地址:https://www.cnblogs.com/lshao/p/14871035.html