1. Overview

In this tutorial, we’ll learn how to compile and auto-generate code with a custom source directory containing protobuf files. We’ll look into the default configuration and how to customize that.

2. Configuration

The Gradle protobuf plugin, by default, looks into the directory src/main/proto to fetch all the proto files to compile and generate the source code for those files. Let’s create a sample proto file:

syntax = "proto3";

package com.baeldung.protobuf;
option java_multiple_files = true;
option java_package = "com.baeldung.protobuf.service";

message User {
    string firstName = 1;
    optional string middleName = 2;
    string lastName = 3;
    optional uint32 age = 4;
}

Let’s save this proto file into some random directory named src/sample_protofiles. We’ll now update our configuration in the build.gradle file so that it’ll include this directory for compiling and generating the source code:

sourceSets {
    main {
        proto {
            srcDir 'src/sample_protofiles'
        }
	//other configuration
    }
    test {
        proto {
            srcDir 'src/sample_protofiles'
        }
    }
}

We can also configure multiple srcDir referring to different directories containing proto files. It’ll include all these proto files in addition to the default src/main/proto directory. It’ll compile all the proto files and generate the source code. We can even configure different directories for main and test source sets.

3. Code Generation and Validation

Let’s generate the code by running the following build command:

gradle build

It’ll create the build directory where the code will be generated.

We can now easily validate the generated code by creating a Java instance of the User class:

final String firstName = "John";
final String lastName = "Doe";
final int age = 28;

User user = User.newBuilder()
  .setFirstName(firstName)
  .setLastName(lastName)
  .setAge(age)
  .build();

assertEquals(firstName, user.getFirstName());
assertEquals(lastName, user.getLastName());
assertEquals(age, user.getAge());

4. Conclusion

In this quick article, we’ve learned how to configure a custom source directory for protobuf files.

As always, the complete source code of the examples is available on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.