1. 程式人生 > 實用技巧 >idea安裝protobuf外掛並生成對應的java檔案

idea安裝protobuf外掛並生成對應的java檔案

搜了很多,然並卵。互相copy居多,試錯好幾次。

直奔主題,springboot專案。

在idea增加外掛。

在pom增加依賴:

<!--protobuf相關-->
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java-util -->
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java-util</artifactId>
            <version>3.5.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.grpc/grpc-all -->
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-all</artifactId>
            <version>1.11.0</version>
        </dependency>
        <!--protobuf相關end-->

  然後在build里加入外掛

 <build>

        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.5.0.Final</version>
            </extension>
        </extensions>

        <plugins>        
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.0</version>
                <configuration>
                    <protocArtifact>
                        com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}
                    </protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>
                        io.grpc:protoc-gen-grpc-java:1.11.0:exe:${os.detected.classifier}
                    </pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

  然後在右側 Maven Projects裡就能看到安裝的外掛了

裝外掛匯入時,會在控制檯看到遠端下載一些包。可能會比較慢。我下載了近10分鐘才下載到。

因為配置中並沒有指明原始檔以及輸出檔案的路徑。此時直接執行protobuf:compile,因為沒有protobuf檔案,看控制檯會提示在專案的src/main/proto下找不到檔案。

那麼此時就可以在該檔案路徑下建立protobuf檔案或者拷貝過來。

有幾個檔案是用到impoer關鍵詞的。例如:

在檔案頭部更改要輸出的包名。然後在idea右邊Pligins選擇 protobuf:compile執行即可。在target就可以看到生成的對應java檔案

先解決能用的問題。剩下的有空再看。