First build tutorials
Bazel Tutorial: Build a Java Project
This tutorial covers the basics of building Java applications with
Bazel. You will set up your workspace and build a simple Java project that
illustrates key Bazel concepts, such as targets and BUILD files.
Estimated completion time: 30 minutes.
What youll learn
In this tutorial you learn how to:
- Build a target
- Visualize the projects dependencies
- Split the project into multiple targets and packages
- Control target visibility across packages
- Reference targets through labels
- Deploy a target
Before you begin
Install Bazel
To prepare for the tutorial, first Install Bazel if
you dont have it installed already.
Install the JDK
-
Install Java JDK (preferred version is 11, however versions between 8 and 15 are supported).
-
Set the JAVA_HOME environment variable to point to the JDK.
-
On Linux/macOS:
export JAVA_HOME=(dirname(dirname (dirname(dirname (realpath(realpath (realpath(which javac))))
-
On Windows:
- Open Control Panel.
- Go to SystemandSecurity > System > AdvancedSystemSettings > Advancedtab > EnvironmentVariables .
- Under the Uservariables list (the one on the top), click New.
- In the Variablename field, enter
JAVA_HOME.
- Click BrowseDirectory.
- Navigate to the JDK directory (for example
C:\Program Files\Java\jdk1.8.0_152).
- Click OK on all dialog windows.
Get the sample project
Retrieve the sample project from Bazels GitHub repository:
The sample project for this tutorial is in the examples/java-tutorial
directory and is structured as follows:
Build with Bazel
Set up the workspace
Before you can build a project, you need to set up its workspace. A workspace is
a directory that holds your projects source files and Bazels build outputs. It
also contains files that Bazel recognizes as special:
-
The
MODULE.bazel file, which identifies the directory and its contents as a
Bazel workspace and lives at the root of the projects directory structure,
-
One or more
BUILD files, which tell Bazel how to build different parts of
the project. (A directory within the workspace that contains a BUILD file
is a package. You will learn about packages later in this tutorial.)
To designate a directory as a Bazel workspace, create an empty file named
MODULE.bazel in that directory.
When Bazel builds the project, all inputs and dependencies must be in the same
workspace. Files residing in different workspaces are independent of one
another unless linked, which is beyond the scope of this tutorial.
Understand the BUILD file
A BUILD file contains several different types of instructions for Bazel.
The most important type is the build rule, which tells Bazel how to build the
desired outputs, such as executable binaries or libraries. Each instance
of a build rule in the BUILD file is called a target and points to a
specific set of source files and dependencies. A target can also point to other
targets.
Take a look at the java-tutorial/BUILD file:
In our example, the ProjectRunner target instantiates Bazels built-in
java_binary rule. The rule tells Bazel to
build a .jar file and a wrapper shell script (both named after the target).
The attributes in the target explicitly state its dependencies and options.
While the name attribute is mandatory, many are optional. For example, in the
ProjectRunner rule target, name is the name of the target, srcs specifies
the source files that Bazel uses to build the target, and main_class specifies
the class that contains the main method. (You may have noticed that our example
uses glob to pass a set of source files to Bazel
instead of listing them one by one.)
Build the project
To build your sample project, navigate to the java-tutorial directory
and run:
In the target label, the // part is the location of the BUILD file
relative to the root of the workspace (in this case, the root itself),
and ProjectRunner is the target name in the BUILD file. (You will
learn about target labels in more detail at the end of this tutorial.)
Bazel produces output similar to the following:
Congratulations, you just built your first Bazel target! Bazel places build
outputs in the bazel-bin directory at the root of the workspace. Browse
through its contents to get an idea for Bazels output structure.
Now test your freshly built binary:
Review the dependency graph
Bazel requires build dependencies to be explicitly declared in BUILD files.
Bazel uses those statements to create the projects dependency graph, which
enables accurate incremental builds.
To visualize the sample projects dependencies, you can generate a text
representation of the dependency graph by running this command at the
workspace root:
The above command tells Bazel to look for all dependencies for the target
//:ProjectRunner (excluding host and implicit dependencies) and format the
output as a graph.
Then, paste the text into GraphViz.
As you can see, the project has a single target that build two source files with
no additional dependencies:
[Dependency graph of the target 'ProjectRunner']
After you set up your workspace, build your project, and examine its
dependencies, then you can add some complexity.
Refine your Bazel build
While a single target is sufficient for small projects, you may want to split
larger projects into multiple targets and packages to allow for fast incremental
builds (that is, only rebuild whats changed) and to speed up your builds by
building multiple parts of a project at once.
Specify multiple build targets
You can split the sample project build into two targets. Replace the contents of
the java-tutorial/BUILD file with the following:
With this configuration, Bazel first builds the greeter library, then the
ProjectRunner binary. The deps attribute in java_binary tells Bazel that
the greeter library is required to build the ProjectRunner binary.
To build this new version of the project, run the following command:
Bazel produces output similar to the following:
Now test your freshly built binary:
If you now modify ProjectRunner.java and rebuild the project, Bazel only
recompiles that file.
Looking at the dependency graph, you can see that ProjectRunner depends on the
same inputs as it did before, but the structure of the build is different:
[Dependency graph of the target 'ProjectRunner' after adding a dependency]
Youve now built the project with two targets. The ProjectRunner target builds
one source files and depends on one other target (:greeter), which builds
one additional source file.
Use multiple packages
Lets now split the project into multiple packages. If you take a look at the
src/main/java/com/example/cmdline directory, you can see that it also contains
a BUILD file, plus some source files. Therefore, to Bazel, the workspace now
contains two packages, //src/main/java/com/example/cmdline and // (since
there is a BUILD file at the root of the workspace).
Take a look at the src/main/java/com/example/cmdline/BUILD file:
The runner target depends on the greeter target in the // package (hence
the target label //:greeter) - Bazel knows this through the deps attribute.
Take a look at the dependency graph:
[Dependency graph of the target 'runner']
However, for the build to succeed, you must explicitly give the runner target
in //src/main/java/com/example/cmdline/BUILD visibility to targets in
//BUILD using the visibility attribute. This is because by default targets
are only visible to other targets in the same BUILD file. (Bazel uses target
visibility to prevent issues such as libraries containing implementation details
leaking into public APIs.)
To do this, add the visibility attribute to the greeter target in
java-tutorial/BUILD as shown below:
Now you can build the new package by running the following command at the root
of the workspace:
Bazel produces output similar to the following:
Now test your freshly built binary:
Youve now modified the project to build as two packages, each containing one
target, and understand the dependencies between them.
Use labels to reference targets
In BUILD files and at the command line, Bazel uses target labels to reference
targets - for example, //:ProjectRunner or
//src/main/java/com/example/cmdline:runner. Their syntax is as follows:
If the target is a rule target, then path/to/package is the path to the
directory containing the BUILD file, and target-name is what you named the
target in the BUILD file (the name attribute). If the target is a file
target, then path/to/package is the path to the root of the package, and
target-name is the name of the target file, including its full path.
When referencing targets at the repository root, the package path is empty,
just use //:target-name. When referencing targets within the same BUILD
file, you can even skip the // workspace root identifier and just use
:target-name.
For example, for targets in the java-tutorial/BUILD file, you did not have to
specify a package path, since the workspace root is itself a package (//), and
your two target labels were simply //:ProjectRunner and //:greeter.
However, for targets in the //src/main/java/com/example/cmdline/BUILD file you
had to specify the full package path of //src/main/java/com/example/cmdline
and your target label was //src/main/java/com/example/cmdline:runner.
Package a Java target for deployment
Lets now package a Java target for deployment by building the binary with all
of its runtime dependencies. This lets you run the binary outside of your
development environment.
As you remember, the java_binary build rule
produces a .jar and a wrapper shell script. Take a look at the contents of
runner.jar using this command:
The contents are:
As you can see, runner.jar contains Runner.class, but not its dependency,
Greeting.class. The runner script that Bazel generates adds greeter.jar
to the classpath, so if you leave it like this, it will run locally, but it
wont run standalone on another machine. Fortunately, the java_binary rule
allows you to build a self-contained, deployable binary. To build it, append
_deploy.jar to the target name:
Bazel produces output similar to the following:
You have just built runner_deploy.jar, which you can run standalone away from
your development environment since it contains the required runtime
dependencies. Take a look at the contents of this standalone JAR using the
same command as before:
The contents include all of the necessary classes to run:
Further reading
For more details, see:
Happy building! Bazel Tutorial: Build a C++ Project
Bazel Tutorial: Build a Go Project