Search code examples
javajargrpcgrpc-javaprotobuf-java

How GRPC .proto file works inside java jar file


I am new to GRPC and writing a sample java function using GRPC, I am using protobuf-maven-plugin to generate java files from my .proto file. Everything works fine on my local development. When I create the executable jar file I noticed at root dir of the jar there exists my .proto file

├───GRpc.proto
├───com
└───META-INF

I wonder do we need this .proto file inside the executable jar? If yes what is it's functionality when running the jar. Thanks.


Solution

  • The .protos are included in .jar to allow using protobuf dependencies as easily as java dependencies. Both protobuf-maven-plugin and protobuf-gradle-plugin support searching dependencies for protos.

    The idea is to have generated code for protos published to Maven Central. Those artifacts contain enough for both java and protobuf.

    The simplest example is protobuf-java itself. Protobuf has "well known protos" like google.protobuf.Any and google.protobuf.Empty. Let's say you make a proto that uses one:

    syntax = "proto3";
    
    package mypackage;
    
    import "google/protobuf/any.proto";
    
    message MyMethod {
      google.protobuf.Any anyField = 1;
    }
    

    To generate code for that .proto, the any.proto file is needed. But to compile generated java code the com.google.protobuf.Any class is needed. Somehow you need two dependencies.

    Placing the .proto in the .jar allows only adding a single dependency to satisfy both the protobuf dependency and the java dependency:

        <dependency>
          <groupId>com.google.protobuf</groupId>
          <artifactId>protobuf-java</artifactId>
          <version>3.21.1</version>
        </dependency>
    

    Protobuf-java is not a special case. For example, https://github.com/googleapis/googleapis publishes generated java code for its protos in artifacts like com.google.api.grpc:proto-google-common-protos. That dependency includes the .protos as well so a single dependency satisfies Protobuf and Java.

    As you make your own protos and publish generated Java code, the protos are included to allow others to create their own protos that depend on yours.