Skip to main content
  1. Posts/

Configuring Protobuf to Java compiler in maven

Table of Contents

Here are few steps to configure protobuf-to-java compilation in your maven project:

Install google protobuf compiler on your computer.

brew install protobuf

Configure maven protobuf compiler plugin and protobuf-java dependency in pom.xml

:

<?xml version='1.0' encoding='UTF-8'?>
<project
    xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd'
    xmlns='http://maven.apache.org/POM/4.0.0'
    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
    
    ... 
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <detail>true</detail>
                    <attachProtoSources>true</attachProtoSources>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
    <dependencies>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.21.7</version>
        </dependency>
    </dependencies>
</project>

Create protobuf definition files within /src/main/proto/ directory. You may want to specify the following options in .proto files.

package com.example;
option java_multiple_files = true;
option java_outer_classname = "Messages";

Run mvn generate-sources and you’re done!