maven-protobuf-plugin 編譯多個protobuf檔案 出現is already defined in,不用替換類名或更改巢狀結構
阿新 • • 發佈:2021-06-10
背景
使用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>