Generate java code from .proto file using gradle

Divya Jaisawal
2 min readMar 27, 2019

--

  1. Dependencies :
compile "com.google.protobuf:protobuf-java:3.6.1"

You can either import

compile group: 'io.grpc', name: 'grpc-all', version: '1.19.0'

or choose only required dependencies from group: ‘io.grpc’ i.e

compile group: 'io.grpc', name: 'grpc-protobuf', version: '1.19.0'
compile group: 'io.grpc', name: 'grpc-stub', version: '1.19.0'
compile group: 'io.grpc', name: 'grpc-netty-shaded', version: '1.19.0'
compile group: 'io.grpc', name: 'grpc-netty', version: '1.19.0'

2. Plugins required :

  • Order of the plugins doesn’t matter.
  • Protocol Buffer plugin assembles the Protobuf Compiler (protoc) command line and use it to generate Java source files out of your proto files and adds the generated Java source files to the input of the corresponding Java compilation unit (sourceSet in a Java project), so that they can be compiled along with your Java sources.
plugins {
id 'java'
id "com.google.protobuf" version "0.8.8"
}

3. Repositories:

repositories {
mavenCentral()
}

4. Source set:

The Protobuf plugin assumes Protobuf files (*.proto) are organized in the same way as Java source files, in sourceSets. The Protobuf files of a sourceSet are compiled in a single protoc run, and the generated files are added to the input of the Java compilation run of that sourceSet ().

sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
}
}

5. Protobuf:

By default the plugin will search for the protoc executable in the system search path. I recommend you to take the advantage of pre-compiled protoc published on maven or you can also provide the path.

Please read this for more details: https://github.com/google/protobuf-gradle-plugin

protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.7.0"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:1.19.0"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}

Complete code:

plugins {
id 'java'
id "com.google.protobuf" version "0.8.8"
}

repositories {
mavenCentral()
}

dependencies {

compile group: 'io.grpc', name: 'grpc-all', version: '1.19.0'
compile "com.google.protobuf:protobuf-java:3.6.1"
}

sourceSets {
main {
java {
srcDirs 'build/generated/source/proto/main/grpc'
srcDirs 'build/generated/source/proto/main/java'
}
}
}


protobuf {
protoc {
artifact = "com.google.protobuf:protoc:3.7.0"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:1.19.0"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
}
}
}

Now run ./gradlew clean build to generate the grpc file. You can see the file at this path build/generated/source/proto/main/grpc

--

--