Generic Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

Bazel is an open-source tool for building and testing source code, similar to Maven and Gradle. It supports projects in multiple languages and builds outputs for multiple platforms.

In this tutorial, we'll go through the steps required to build a simple Java application using Bazel. For illustration, we'll begin with a multi-module Maven project and then build the source code using Bazel.

We'll start by installing Bazel.

2. Project Structure

Let's create a multi-module Maven project:

bazel (root)
    pom.xml
    WORKSPACE (bazel workspace)
    |— bazelapp
        pom.xml
        BUILD (bazel build file)
        |— src
            |— main
                |— java
            |— test
                |— java
    |— bazelgreeting
        pom.xml
        BUILD (bazel build file)
        |— src
            |— main
                |— java
            |— test
                |— java

The presence of the WORKSPACE file sets up the workspace for Bazel. There could be one or a multiple of them in a project. For our example, we'll keep only one file at the top-level project directory.

The next important file is the BUILD file, which contains the build rules. It identifies each rule with a unique target name.

Bazel offers the flexibility to have as many BUILD files as we need, configured to any level of granularity. This would mean we can build a smaller number of Java classes by configuring BUILD rules accordingly. To keep things simple, we will keep minimal BUILD files in our example.

Since the output of the Bazel BUILD configuration is typically a jar file, we'll refer each directory containing the BUILD file as a build package.

3. Build File

3.1. Rule Configuration

It's time to configure our first build rule to build the Java binaries. Let's configure one in the BUILD file belonging to the bazelapp module:

java_binary (
    name = "BazelApp",
    srcs = glob(["src/main/java/com/baeldung/*.java"]),
    main_class = "com.baeldung.BazelApp"
)

Let's understand the configuration settings one-by-one:

  • java_binary – the name of the rule; it requires additional attributes for building the binaries
  • name – the name of the build target
  • srcs – an array of the file location patterns that tell which Java files to build
  • main_class – the name of the application main class (optional)

3.2. Build Execution

We are now good to build the app. From the directory containing the WORKSPACE file, let's execute the bazel build command in a shell to build our target:

$ bazel build //bazelapp:BazelApp

The last argument is the target name configured in one of the BUILD files. It has the pattern “//<path_to_build>:<target_name>“.

The first part of the pattern, “//”, indicates we're starting in our workspace directory. The next, “bazelapp”, is the relative path to the BUILD file from the workspace directory. Finally, “BazelApp” is the target name to build.

3.3. Build Output

We should now notice two binary output files from the previous step:

bazel-bin/bazelapp/BazelApp.jar
bazel-bin/bazelapp/BazelApp

The BazelApp.jar contains all the classes, while BazelApp is a wrapper script to execute the jar file.

3.4. Deployable JAR

We may need to ship the jar and its dependencies to different locations for deployment.

The wrapper script from the section above specifies all the dependencies (jar files) as part of BazelApp.jar‘s startup command.

However, we can also make a fat jar containing all the dependencies:

$ bazel build //bazelapp:BazelApp_deploy.jar

Suffixing the name of the target with “_deploy” instructs Bazel to package all the dependencies within the jar and make it ready for deployment.

4. Dependencies

So far, we've only built using the files in bazelapp. But, most every app has dependencies.

In this section, we'll see how to package the dependencies together with the jar file.

4.1. Building Libraries

Before we do that, though, we need a dependency that bazelapp can use.

Let's create another Maven module named bazelgreeting and configure the BUILD file for the new module with the java_library rule. We'll name this target “greeter”:

java_library (
    name = "greeter",
    srcs = glob(["src/main/java/com/baeldung/*.java"])
)

Here, we've used the java_library rule for creating the library. After building this target, we'll get the libgreetings.jar file:

INFO: Found 1 target...
Target //bazelgreeting:greetings up-to-date:
  bazel-bin/bazelgreeting/libgreetings.jar

4.2. Configuring Dependencies

To use greeter in bazelapp, we'll need some additional configurations. First, we need to make the package visible to bazelapp. We can achieve this by adding the visibility attribute in the java_library rule of the greeter package:

java_library (
    name = "greeter",
    srcs = glob(["src/main/java/com/baeldung/*.java"]),
    visibility = ["//bazelapp:__pkg__"]
)

The visibility attribute makes the current package visible to those listed in the array.

Now in the bazelapp package, we must configure the dependency on the greeter package. Let's do this with the deps attribute:

java_binary (
    name = "BazelApp",
    srcs = glob(["src/main/java/com/baeldung/*.java"]),
    main_class = "com.baeldung.BazelApp",
    deps = ["//bazelgreeting:greeter"]
)

The deps attribute makes the current package dependent on those listed in the array.

5. External Dependencies

We can work on projects that have multiple workspaces and depend on each other. Or, we can import libraries from remote locations. We can categorize such external dependencies as:

  • Local Dependencies: We manage them within the same workspace as we have seen in the previous section or span across multiple workspaces
  • HTTP Archives: We import the libraries from a remote location over HTTP

There are many Bazel rules available to manage external dependencies. We'll see how to import jar files from the remote location in the subsequent sections.

5.1. HTTP URL Locations

For our example, let's import Apache Commons Lang into our application. Since we have to import this jar from the HTTP location, we will use the http_jar rule. We'll first load the rule from the Bazel HTTP build definitions and configure it in the WORKSPACE file with Apache Commons's location:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_jar")

http_jar (
    name = "apache-commons-lang",
    url = "https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar"
)

We must further add dependencies in the BUILD file of the “bazelapp” package:

deps = ["//bazelgreeting:greeter", "@apache-commons-lang//jar"]

Note, we need to specify the same name used in the http_jar rule from the WORKSPACE file.

5.2. Maven Dependencies

Managing individual jar files becomes a tedious task. Alternatively, we can configure the Maven repository using the rules_jvm_external rule in our WORKSPACE file. This will enable us to fetch as many dependencies we want in our project from repositories.

First, we must import the rules_jvm_external rule from a remote location using the http_archive rule in the WORKSPACE file:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

RULES_JVM_EXTERNAL_TAG = "2.0.1"
RULES_JVM_EXTERNAL_SHA = "55e8d3951647ae3dffde22b4f7f8dee11b3f70f3f89424713debd7076197eaca"

http_archive(
    name = "rules_jvm_external",
    strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
    sha256 = RULES_JVM_EXTERNAL_SHA,
    url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
)

Next, we'll use the maven_install rule and configure the Maven repository URL and the required artifacts:

load("@rules_jvm_external//:defs.bzl", "maven_install")

maven_install(
    artifacts = [
        "org.apache.commons:commons-lang3:3.9" ], 
    repositories = [ 
        "https://repo1.maven.org/maven2", 
    ] )

At last, we'll add the dependency in the BUILD file:

deps = ["//bazelgreeting:greeter", "@maven//:org_apache_commons_commons_lang3"]

It resolves the names of the artifacts using underscore (_) characters.

6. Conclusion

In this tutorial, we learned basic configurations to build a Maven style Java project with the Bazel build tool.

The source code is also available over GitHub. It exists as a Maven project and is also configured with the Bazel WORKSPACE and BUILD files.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!