TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › Java: java_library & java_binary

Java: java_library & java_binary

Java is where Bazel's design pays off most visibly: Maven and Gradle compile a whole module at a time, while Bazel compiles each java_library separately against the interface jars (-hjar/-ijar, class files with method bodies stripped) of its dependencies. A change inside a method body doesn't change the interface jar, so dependents are not recompiled. The rules come from rules_java (9.9.0 here):

Rule Produces
java_library lib<name>.jar (+ a header jar for dependents, + a source jar on request)
java_binary a launcher script, <name>.jar, and on request <name>_deploy.jar, a single runnable jar with all dependencies
java_test a test run by bazel test, normally through JUnit
java_import wraps prebuilt jars

The course image runs every Java action on a remote JDK 21 that Bazel downloaded as a toolchain (--java_runtime_version=remotejdk_21 in /etc/bazel.bazelrc); no JDK is installed in the container itself.

A library and a binary

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_java", version = "9.9.0")' > MODULE.bazel
mkdir -p java/com/example/money java/com/example/app
cat > java/com/example/money/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_library", "java_test")

java_library(
    name = "money",
    srcs = ["Money.java"],
    visibility = ["//visibility:public"],
)

java_test(
    name = "MoneyTest",
    size = "small",
    srcs = ["MoneyTest.java"],
    use_testrunner = False,          # no JUnit in this image: main() is the test
    main_class = "com.example.money.MoneyTest",
    deps = [":money"],
)
EOF
cat > java/com/example/money/Money.java <<'EOF'
package com.example.money;

public final class Money {
  private Money() {}

  public static String format(long cents) {
    return String.format("$%d.%02d", cents / 100, cents % 100);
  }
}
EOF
cat > java/com/example/money/MoneyTest.java <<'EOF'
package com.example.money;

public class MoneyTest {
  public static void main(String[] args) {
    String got = Money.format(1999);
    if (!got.equals("$19.99")) {
      System.err.println("expected $19.99, got " + got);
      System.exit(1);
    }
    System.out.println("MoneyTest passed");
  }
}
EOF
cat > java/com/example/app/BUILD.bazel <<'EOF'
load("@rules_java//java:defs.bzl", "java_binary")

java_binary(
    name = "app",
    srcs = ["App.java"],
    main_class = "com.example.app.App",
    deps = ["//java/com/example/money"],
)
EOF
cat > java/com/example/app/App.java <<'EOF'
package com.example.app;

import com.example.money.Money;

public class App {
  public static void main(String[] args) {
    System.out.println("Total: " + Money.format(4250) + " on Java " + Runtime.version().feature());
  }
}
EOF
bazel run //java/com/example/app 2>&1 | grep -E 'processes|Total'
bazel test //java/com/example/money:MoneyTest 2>&1 | grep -E 'PASSED|FAILED'
bazel build //java/com/example/app:app_deploy.jar 2>/dev/null
unzip -Z1 bazel-bin/java/com/example/app/app_deploy.jar | grep -v '/
  

 | sort
INFO: 11 processes: 6 internal, 3 processwrapper-sandbox, 2 worker.
Total: $42.50 on Java 21
//java/com/example/money:MoneyTest                                       PASSED in 0.1s
META-INF/MANIFEST.MF
build-data.properties
com/example/app/App.class
com/example/money/Money.class

Notes:

  • Java packages map to directories: Bazel finds the Java root by looking for a java/ or javatests/ path segment (or src/main/java), so java/com/example/money/Money.java is class com.example.money.Money. Set resource_strip_prefix or put sources under such a root.
  • 2 worker in the summary: Bazel runs javac in a persistent worker, a long-lived JVM that compiles many targets, avoiding JVM start-up per action. Workers are why Java builds under Bazel are fast after the first one.
  • app_deploy.jar is an implicit output: it's only built when requested. It contains your classes plus every dependency (and a small build-data.properties with build information), ready for java -jar. Ship this, not app.jar.
  • A real java_test uses JUnit: drop use_testrunner/main_class, set test_class, and add JUnit from Maven (below). The image has no Maven artifacts for Bazel, so the test here is a plain main that exits non-zero on failure, which is all bazel test needs.

Maven dependencies (not run here)

Third-party jars usually come from rules_jvm_external, which resolves Maven coordinates, writes a lock file (maven_install.json) and creates one target per artifact:

python
bazel_dep(name = "rules_jvm_external", version = "6.7")

maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
maven.install(
    artifacts = [
        "com.google.guava:guava:33.5.0-jre",
        "org.junit.jupiter:junit-jupiter-api:5.14.4",
    ],
    lock_file = "//:maven_install.json",
    repositories = ["https://repo1.maven.org/maven2"],
)
use_repo(maven, "maven")
python
java_library(
    name = "inventory",
    srcs = glob(["*.java"]),
    deps = ["@maven//:com_google_guava_guava"],
)

bazel run @maven//:pin refreshes the lock file. Unlike Maven, Bazel requires every direct dependency to be listed: compiling against a class that only comes transitively fails with a strict deps error that prints the buildozer command to add the missing dep. Migrating Gradle/Maven shows how teams move existing builds over.

Test yourself

Why don't dependents of a java_library recompile when only a method body changes?

  1. Bazel ignores Java changes
  2. Dependents compile against the library's interface (header) jar, which doesn't change
  3. javac is incremental
  4. Tests are skipped

Which output of java_binary(name = "app") is a single runnable jar with all dependencies?

  1. app.jar
  2. app_deploy.jar
  3. libapp.jar
  4. app-all.jar

What is a 'strict deps' error in Bazel's Java rules?

  1. A missing JDK
  2. Code uses a class from a dependency that is not listed directly in deps
  3. A visibility error
  4. A failing test