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 '/