### Example: Creating a Distribution JAR Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md This example shows how to bundle multiple internal libraries and specify a main class for a distribution-ready JAR. ```starlark java_single_jar( name = "dist", jars = [ ":app", ":models", ":utils", ], main_class = "com.example.App", output = "myapp-dist.jar", ) ``` -------------------------------- ### Example: Versioning with Manifest Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Illustrates how to include version and build date information directly into the JAR manifest using manifest_lines. ```starlark java_single_jar( name = "versioned", jars = [":app"], main_class = "com.example.App", manifest_lines = [ "Implementation-Version: 2.1.0", "Build-Date: 2024-01-15", ], ) ``` -------------------------------- ### Example: Merging JARs Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Demonstrates how to merge a custom java_library and its dependency into a single output JAR named 'combined.jar'. ```starlark java_library( name = "mylib", srcs = glob(["src/**/*.java"]), deps = [":dependency"], ) java_single_jar( name = "combined", jars = [ ":mylib", ":dependency", ], output = "combined.jar", ) ``` -------------------------------- ### Bazel Build Command Example Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/INDEX.md Example of a Bazel command to build a Java target, specifying a Java toolchain. This demonstrates how to configure the Java compiler version for the build. ```bash bazel build //target --java_toolchain=//tools:java17 ``` -------------------------------- ### Example: Legacy Library Distribution Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Shows how to bundle legacy libraries along with resource files like LICENSE.txt and NOTICE.txt into a single JAR. ```starlark java_single_jar( name = "legacy_bundle", jars = [ ":main_lib", ":compat_lib", ], resources = [ "LICENSE.txt", "NOTICE.txt", ], output = "legacy.jar", ) ``` -------------------------------- ### Multi-Package Configuration Example Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Defines distinct compiler configurations for multiple sets of packages. This example shows strict settings for core packages and lenient settings for experimental ones. ```starlark java_package_configuration( name = "strict_packages", packages = [ "com.example.api", "com.example.core", "com.example.services", ], javacopts = ["-Werror", "-Xlint:all"], ) java_package_configuration( name = "experimental_packages", packages = [ "com.example.experimental.*", ], javacopts = ["-Xlint:none"], ) java_toolchain( name = "tiered_toolchain", package_configurations = [ ":strict_packages", ":experimental_packages", ], # ... rest of toolchain config ... ) ``` -------------------------------- ### Simple java_binary Example Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_binary.md Defines a basic Java executable application with source files, main class, and library dependencies. ```starlark java_binary( name = "app", srcs = ["Main.java"], main_class = "com.example.Main", deps = [ ":lib", ], ) java_library( name = "lib", srcs = glob(["lib/**/*.java"]), ) ``` -------------------------------- ### Example: Testing with Bundled Dependencies Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Demonstrates creating a JAR for testing that includes test code and necessary testing libraries like JUnit and Mockito. ```starlark java_single_jar( name = "test_bundle", jars = [ ":test_lib", "@maven//:junit_junit", "@maven//:mockito_mockito_core", ], output = "test-with-deps.jar", ) ``` -------------------------------- ### Example java_plugin Rule Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md Demonstrates how the `java_plugin` rule automatically creates a JavaPluginInfo provider. This includes the processor JAR, its class name, and any dependencies. ```starlark java_plugin( name = "my_processor", srcs = ["MyProcessor.java"], processor_class = "com.example.MyProcessor", deps = [ "@maven//:javax_annotation_api", ], ) # This produces a target providing JavaPluginInfo with: # - processor_jars: lib.my_processor.jar # - processor_classes: ["com.example.MyProcessor"] # - data: [] ``` -------------------------------- ### Basic java_test Configuration Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_test.md A simple example of a `java_test` rule, specifying source files, the main test class, and dependencies. ```starlark java_test( name = "mylib_test", srcs = glob(["*_test.java"]), test_class = "com.example.MyTest", deps = [ ":mylib", "@maven//:junit_junit", ], ) ``` -------------------------------- ### Example: Creating a Fat JAR Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Shows how to create a fat JAR that includes application code and external Maven dependencies like Guava and JUnit, specifying the main class. ```starlark java_single_jar( name = "app_fat", jars = [ ":app", "@maven//:com_google_guava_guava", "@maven//:junit_junit", ], main_class = "com.example.Main", output = "app-with-deps.jar", ) ``` -------------------------------- ### Example Javac Options Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_library.md Illustrates how to pass additional compiler options to javac for a specific java_library target. These options are appended to global compiler options. ```starlark java_library( name = "my_library", srcs = ["MyClass.java"], javacopts = ["-Werror", "-Xlint:unchecked"], deps = [ "//:some_dependency", ], ) ``` -------------------------------- ### Example: With Custom Manifest Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_single_jar.md Illustrates how to add custom entries to the JAR manifest, such as implementation title, version, and custom headers, alongside the main class. ```starlark java_single_jar( name = "release_jar", jars = [":app"], main_class = "com.example.Application", manifest_lines = [ "Implementation-Title: MyApp", "Implementation-Version: 1.0.0", "X-Custom-Header: custom-value", ], output = "myapp-1.0.0.jar", ) ``` -------------------------------- ### Tokenization of javacopts Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Demonstrates how javacopts are tokenized. The first example shows simple tokenization, while the second preserves shell escaping for values with spaces. ```starlark javacopts = ["-J-Xmx1G -J-Xms512M"] # Becomes ["-J-Xmx1G", "-J-Xms512M"] ``` ```starlark javacopts = ["-Dprop='value with spaces'"] # Shell escaping preserved ``` -------------------------------- ### Custom Plugin Creation Implementation Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md An example implementation for creating a custom plugin that returns a `JavaPluginInfo` provider. This involves compiling the processor code and packaging it with metadata. ```starlark def _my_plugin_info_impl(ctx): # Compile processor code jar = ctx.actions.declare_file("processor.jar") # ... compilation action ... # Create JavaPluginInfo plugin_info = JavaPluginInfo( processor_jars = depset([jar]), processor_classes = depset(["com.example.MyProcessor"]), data = depset(ctx.files.data), ) return [plugin_info, DefaultInfo(files = depset([jar]))] ``` -------------------------------- ### Simple java_import Example Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_import.md Import a single JAR file and make it available as a dependency. This is useful for libraries without associated source JARs or complex dependency trees. ```starlark java_import( name = "guava", jars = ["guava-31.1-jre.jar"], ) java_library( name = "mylib", srcs = ["Source.java"], deps = [":guava"], ) ``` -------------------------------- ### Java Library Rule Example Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/INDEX.md Example of defining a java_library rule in Starlark. This is used for compiling Java source files. ```starlark java_library( name = "example", srcs = ["Source.java"], ) ``` -------------------------------- ### Define Custom JDK Distribution with http_archive Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_runtime.md This example demonstrates how to use `http_archive` to download and define a custom JDK distribution. It includes a `build_file_content` to properly expose the JDK as a filegroup. ```python # MODULE.bazel load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "my_jdk", urls = ["https://example.com/my_jdk_11.tar.gz"], sha256 = "...", build_file_content = """ filegroup( name = "jdk", srcs = glob(["**/*"]), visibility = ["//visibility:public"], ) """, ) java_runtime( name = "custom_jdk11", java_home = "@my_jdk//:jdk", version = 11, ) register_toolchains( "//toolchains:with_custom_jdk", ) ``` -------------------------------- ### Custom Annotation Processor Setup Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_plugin.md Define annotation definitions, the processor implementation using `java_plugin` with `processor_class`, and a library that uses the processor via the `plugins` attribute. ```starlark # BUILD file # The annotation definitions java_library( name = "annotations", srcs = ["Marker.java"], # Simple @interface ) # The processor implementation java_plugin( name = "marker_processor", srcs = ["MarkerProcessor.java"], processor_class = "com.example.MarkerProcessor", deps = [ ":annotations", "@bazel_tools//tools/jdk:jdk-default", ], ) # A library using the processor java_library( name = "marked_lib", srcs = ["Service.java"], plugins = [":marker_processor"], deps = [":annotations"], ) # Code in Service.java can use @Marker annotation # MarkerProcessor.java generates additional code based on annotations ``` -------------------------------- ### Using JavaInfo in Dependent Rules Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md This example illustrates how a rule can consume JavaInfo providers from its dependencies. It shows how to iterate through dependencies, check for the presence of JavaInfo, and extract transitive runtime JARs to build a classpath. ```starlark def _consumer_rule_impl(ctx): # Collect all runtime JARs from dependencies runtime_jars = [] for dep in ctx.attr.deps: if JavaInfo in dep: runtime_jars.extend(dep[JavaInfo].transitive_runtime_jars.to_list()) # Use collected JARs in build action classpath_file = ctx.actions.declare_file("classpath.txt") ctx.actions.write( classpath_file, content = ":".join([jar.path for jar in runtime_jars]), ) ``` -------------------------------- ### Creating a JavaInfo Provider Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md This example demonstrates how to create a custom JavaInfo provider within a Starlark rule implementation. It shows how to extract information from a compilation result and construct a new JavaInfo with specific fields populated. ```starlark def _my_rule_impl(ctx): # Compile sources to output.jar output_jar = ctx.actions.declare_file("lib{}.jar".format(ctx.label.name)) # Compile using java_common compile_result = java_common.compile( ctx, source_jars = ctx.files.srcs, output = output_jar, java_toolchain = java_toolchain, # ... other compilation parameters ) # Extract JavaInfo from compilation result java_info = compile_result # Create custom JavaInfo with additional information custom_java_info = JavaInfo( output_jar = output_jar, compile_jar = output_jar, source_jar = source_jar, compile_jars = depset([output_jar]), transitive_runtime_jars = java_info.transitive_runtime_jars, transitive_compile_time_jars = depset([output_jar], transitive=[java_info.transitive_compile_time_jars]), ) return [custom_java_info, DefaultInfo(files = depset([output_jar]))] ``` -------------------------------- ### Define Local JDK Runtime Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_runtime.md Configures a `java_runtime` using a local JDK installation. The `java_home` attribute points to the root directory of the JDK. ```starlark # Typically generated by rules_java, but can be manual: java_runtime( name = "local_jdk", java_home = "/usr/lib/jvm/java-11-openjdk", version = 11, ) ``` -------------------------------- ### http_jar Rule with Mirror URLs Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Example of using the http_jar rule to download a JAR file, providing multiple URLs for redundancy. Bazel will attempt to download from these URLs sequentially. ```python http_jar( name = "lib", urls = [ "https://example.com/lib.jar", # Primary source "https://backup.example.com/lib.jar", # Backup "https://mirror.bazel.build/example.com/lib.jar", # Bazel mirror ], sha256 = "...", ) ``` -------------------------------- ### Example: Strict Checking for API Package Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Configures strict compiler options for the 'com.example.api' package and its subpackages. Use this to enforce error-free code and all lint warnings for critical API code. ```starlark java_package_configuration( name = "api_strict", packages = [ "com.example.api", "com.example.api.*", ], javacopts = [ "-Werror", "-Xlint:all", ], ) ``` -------------------------------- ### Example: Legacy Code with Warnings Disabled Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Configures lenient compiler options for the 'com.example.legacy' package and its subpackages. Use this to disable lint warnings and suppress all warnings for older codebases. ```starlark java_package_configuration( name = "legacy_lenient", packages = [ "com.example.legacy.*", ], javacopts = [ "-Xlint:none", "-nowarn", ], ) ``` -------------------------------- ### ServiceLoader Plugin Configuration Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md Example of configuring a `java_plugin` for processors that use Java's ServiceLoader mechanism, such as Error Prone. The `processor_class` is omitted in this case. ```starlark java_plugin( name = "error_prone", srcs = glob(["src/**/*.java"]), resources = ["service_loader_descriptor"], # Do not specify processor_class for ServiceLoader-based plugins ) # service_loader_descriptor contains: # META-INF/services/javax.annotation.processing.Processor # com.google.errorprone.ErrorPronePlugin ``` -------------------------------- ### Custom Annotation Processor Setup Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/overview.md Defines a Java annotation processor and a library that uses it. The `java_plugin` rule registers the processor, and `java_library` includes it via the `plugins` attribute. ```starlark java_plugin( name = "processor", srcs = ["Processor.java"], processor_class = "com.example.Processor", ) java_library( name = "annotated", srcs = ["Source.java"], plugins = [":processor"], ) ``` -------------------------------- ### Use Case: Framework-Specific Configuration Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Defines different compiler configurations tailored for specific frameworks used within the project. This example sets deprecation warnings for Spring packages and strict checks for internal application code. ```starlark java_package_configuration( name = "spring_config", packages = [ "org.springframework.*", ], javacopts = [ "-Xlint:deprecation", # Spring has many deprecated APIs ], ) java_package_configuration( name = "app_config", packages = [ "com.mycompany.*", ], javacopts = [ "-Werror", "-Xlint:all", ], ) ``` -------------------------------- ### Applying Package Configurations via Bazel Build Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Demonstrates how to apply a configured Java toolchain, which includes package configurations, to a Bazel build target. ```bash bazel build //target --java_toolchain=//toolchains:tiered_toolchain ``` -------------------------------- ### Access Java Toolchain and Runtime Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-common.md Demonstrates how to load semantics and find the Java toolchain and runtime using the provided utility functions. This is a prerequisite for using many java_common functions. ```starlark load("//java/common:java_semantics.bzl", "semantics") java_toolchain = semantics.find_java_toolchain(ctx) java_runtime = semantics.find_java_runtime_toolchain(ctx) ``` -------------------------------- ### Get Default Javac Options Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-common.md Retrieve the default javac options from a Java toolchain using default_javac_opts. These options can be combined with custom options. ```starlark opts = java_common.default_javac_opts(java_toolchain) all_opts = opts + ctx.attr.javacopts ``` -------------------------------- ### java_binary for Distribution Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_binary.md Prepares a Java binary for distribution by enabling stamping and building it as a deploy JAR. The deploy JAR can be executed directly using `java -jar`. ```starlark java_binary( name = "cli", srcs = ["Cli.java"], main_class = "com.example.Cli", stamp = 1, # Include build info deps = [ ":libraries", ], ) # Build: bazel build //path:cli_deploy.jar # Run: java -jar bazel-bin/path/cli_deploy.jar ``` -------------------------------- ### Using Downloaded JAR Directly Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Shows how to directly use a target provided by the http_jar repository if it defines one (e.g., a default java_import). ```starlark java_test( name = "my_test", srcs = ["Test.java"], deps = ["@junit_jar//:lib"], ) ``` -------------------------------- ### Assembling Java Arguments Source: https://github.com/bazelbuild/rules_java/blob/master/java/bazel/rules/java_stub_template.txt Constructs the final array of arguments for the Java command. This includes debugging flags, JVM flags, main advice, and the start class. ```bash ARGS=( ${JVM_DEBUG_FLAGS} ${JVM_FLAGS} %jvm_flags% "${JVM_FLAGS_CMDLINE[@]}" ${MAIN_ADVICE} %java_start_class% "${ARGS[@]}" ) ``` -------------------------------- ### Using Plugins in Java Rules Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md Shows how to apply a `JavaPluginInfo` provider to a `java_library` target using the `plugins` attribute. ```starlark java_library( name = "annotated_lib", srcs = ["Source.java"], plugins = [":my_processor"], ) ``` -------------------------------- ### Configure Java Tools Repositories Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Set up necessary Java tools and remote JDK repositories by calling java_tools_repos() and remote_jdk17_repos(). ```python load(@rules_java//java:repositories.bzl", "java_tools_repos", "remote_jdk17_repos") java_tools_repos() remote_jdk17_repos() ``` -------------------------------- ### Import JavaPluginInfo Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md Load the JavaPluginInfo provider definition from the rules_java repository. ```starlark load("@rules_java//java:defs.bzl", "JavaPluginInfo") ``` -------------------------------- ### Set JAVABIN and Handle --print_javabin Source: https://github.com/bazelbuild/rules_java/blob/master/java/bazel/rules/java_stub_template.txt This snippet sets the `JAVABIN` variable to the path of the JVM launcher. It also includes logic to print the `JAVABIN` path if the `--print_javabin` flag is set. ```bash # Set JAVABIN to the path to the JVM launcher. %javabin% if [[ "$PRINT_JAVABIN" == 1 || "%java_start_class%" == "--print_javabin" ]]; then echo -n "$JAVABIN" exit 0 fi ``` -------------------------------- ### Package Name Type Alias Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/types-reference.md Defines the PackageName type alias as a string, used for Java package names. Examples include 'com.example' and 'org.springframework.core', often used for annotation processor discovery. ```starlark # Java package name PackageName = string # Examples: "com.example", "org.springframework.core" # Used for annotation processor discovery and configuration ``` -------------------------------- ### Compiling Sources with java_common Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md Demonstrates how to use the `java_common.compile()` function to compile Java sources, obtaining a `JavaInfo` result that includes compilation and source JARs. ```starlark result = java_common.compile( ctx, source_jars = ctx.files.srcs, source_files = ctx.files.sources, output = output_jar, output_source_jar = source_jar, deps = ctx.attr.deps, plugins = ctx.attr.plugins, java_toolchain = java_toolchain, ) # result contains JavaInfo ``` -------------------------------- ### Wrapping External Binaries with Runtime Dependencies Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_import.md Demonstrates how to use `java_import` to include an external JAR and also specify runtime dependencies, such as native libraries (`.so` files) provided by a `cc_library`. This is useful for Java applications that rely on native code. ```starlark java_import( name = "external_lib", jars = ["external.jar"], runtime_deps = [ ":native_libs", # cc_library providing .so files ], ) ``` -------------------------------- ### Module Specification Type Alias Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/types-reference.md Defines the ModuleSpec type alias as a string, used for Java module specifications for flags like --add-exports and --add-opens. The format is 'module/package', with examples like 'java.base/java.lang'. ```starlark # Java module specification for --add-exports/--add-opens ModuleSpec = string # Format: "module/package" # Examples: "java.base/java.lang", "jdk.compiler/com.sun.tools.javac.api" ``` -------------------------------- ### Development build environment configuration Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Sets up a development build environment with warnings for Java dependencies and disables Java header compilation. ```bash bazel build //... \ --strict_java_deps=warn \ --java_header_compilation=False ``` -------------------------------- ### Importing Multiple JARs Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_import.md Demonstrates how to specify multiple JAR files within a single java_import target. This is useful for libraries that distribute their components across several JARs. ```starlark java_import( name = "commons", jars = [ "commons-lang3-3.12.0.jar", "commons-io-2.11.0.jar", ], ) ``` -------------------------------- ### Adding Module and Package Exports to JavaInfo Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md Illustrates creating a `JavaInfo` provider and including `add_exports` and `add_opens` attributes. These fields are used to manage module and package visibility and access. ```starlark java_info = JavaInfo( output_jar = output_jar, compile_jar = output_jar, add_exports = ctx.attr.add_exports, add_opens = ctx.attr.add_opens, # ... other fields ) ``` -------------------------------- ### Defining Multiple JARs with http_jar Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Illustrates how to define multiple http_jar rules to download separate JAR files. Each rule is for a distinct library. ```python load("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "junit", urls = ["https://repo1.maven.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar"], sha256 = "8e495b634469d64fb8acfa3495a065cdc1d38dda7eccda76921b8b9f31f9cc81", ) http_jar( name = "hamcrest", urls = ["https://repo1.maven.org/maven2/org/hamcrest/hamcrest/2.2/hamcrest-2.2.jar"], sha256 = "1820c0524dae3d39427df54fdd3f55f190ee461985498e2dBD8b1271c3fef0c2", ) ``` -------------------------------- ### Accessing JavaInfo Provider Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md Demonstrates the basic syntax for accessing the `JavaInfo` provider from a target. This is the primary method for retrieving Java-specific information about a target. ```starlark java_info = target[JavaInfo] ``` -------------------------------- ### Construct Classpath for Single Jar or Runfiles Source: https://github.com/bazelbuild/rules_java/blob/master/java/bazel/rules/java_stub_template.txt This code block constructs the CLASSPATH. If `SINGLEJAR` is 1, it points to the deploy jar. Otherwise, it constructs a classpath relative to the runfiles directory. ```bash if [[ "$SINGLEJAR" == 1 ]]; then CLASSPATH="${self}_deploy.jar" # Check for the deploy jar now. If it doesn't exist, we can print a # more helpful error message than the JVM. [[ -r "$CLASSPATH" ]] \ || die "Option --singlejar was passed, but %s does not exist.\n (You may need to build it explicitly.)" "$CLASSPATH" else # Create the shortest classpath we can, by making it relative if possible. RUNPATH="${JAVA_RUNFILES}/%workspace_prefix%" RUNPATH="${RUNPATH#$PWD/}" CLASSPATH=%classpath% fi # Export the locations which will be used to find the location of the classes from the classpath file. export SELF_LOCATION="$self" export CLASSLOADER_PREFIX_PATH="${RUNPATH}" ``` -------------------------------- ### Java Library with Resources Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_library.md Configures a Java library to include resource files and specify a prefix for stripping during packaging. Useful for libraries with configuration files or assets. ```starlark java_library( name = "utils", srcs = ["Utils.java"], resources = ["config.properties"], resource_strip_prefix = "src/main/resources", ) ``` -------------------------------- ### Java Binary with Dependencies Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/overview.md Defines a Java application executable. Specify the main class and link necessary libraries. ```starlark java_binary( name = "app", srcs = ["Main.java"], main_class = "com.example.Main", deps = [":mylib"], ) ``` -------------------------------- ### java_binary with JVM Configuration Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_binary.md Configures a Java binary with specific JVM flags for memory allocation and network preferences. ```starlark java_binary( name = "server", srcs = ["Server.java"], main_class = "com.example.Server", jvm_flags = [ "-Xmx2G", "-Xms512M", "-Djava.net.preferIPv4Stack=true", ], deps = [ ":server_lib", ], ) ``` -------------------------------- ### Using Downloaded JAR with java_import Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Demonstrates how to reference a JAR downloaded by http_jar within a java_import rule. This makes the JAR available for Java compilation and testing. ```starlark load("@rules_java//java:java_import.bzl", "java_import") java_import( name = "junit", jars = ["@junit_jar//:junit.jar"], # or auto-generated name ) java_test( name = "my_test", srcs = ["Test.java"], deps = [":junit"], ) ``` -------------------------------- ### Select Java Toolchain Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_toolchain.md Specify a custom Java toolchain for a Bazel build using the --java_toolchain flag. ```bash bazel build //target --java_toolchain=//path:my_toolchain ``` -------------------------------- ### Plugin Dependencies Implementation Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md Illustrates how to create a plugin that depends on other plugins, aggregating their processor classes. This allows for modular plugin development. ```starlark def _plugin_with_deps_impl(ctx): # Get processor classes from dependency plugins dep_classes = depset( transitive=[ dep[JavaPluginInfo].processor_classes for dep in ctx.attr.plugins if JavaPluginInfo in dep ] ) # Combine with own classes all_classes = depset( ["com.example.Main"], transitive=[dep_classes] ) return [JavaPluginInfo( processor_jars = depset([my_jar]), processor_classes = all_classes, )] ``` -------------------------------- ### Gradle-Compatible Toolchain Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_toolchain.md Sets up a Java toolchain configured for compatibility with Gradle builds, including debug info and disabled warnings. ```starlark java_toolchain( name = "gradle_compatible", source_version = "11", target_version = "11", javacopts = [ "-g", # Generate debug info "-nowarn", ], jvm_flags = [ "-Dfile.encoding=UTF-8", ], java_runtime = "@openjdk11//:java_runtime", javac = "@java_tools//:javac", javabuilder = "@java_tools//:javabuilder", header_compiler = "@java_tools//:header_compiler", singlejar = "@java_tools//:singlejar", ijar = "@java_tools//:ijar", ) ``` -------------------------------- ### Configure JVM Runtime Options Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Control JVM behavior at runtime by setting jvm_flags in a java_binary rule. ```starlark java_binary( name = "app", srcs = ["Main.java"], jvm_flags = [ "-Xmx4G", "-Xms512M", "-Dfile.encoding=UTF-8", ], ) ``` -------------------------------- ### Compute SHA-256 Checksum Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Demonstrates how to compute the SHA-256 checksum for a JAR file using common command-line tools on macOS/Linux. ```bash # On macOS/Linux sha256sum file.jar # Or using OpenSSL openssl dgst -sha256 file.jar # Online verification echo "sha256" | shasum -c - ``` -------------------------------- ### Prepending Main Advice Classpath Source: https://github.com/bazelbuild/rules_java/blob/master/java/bazel/rules/java_stub_template.txt Adds the MAIN_ADVICE_CLASSPATH to the beginning of the CLASSPATH if it is set. This ensures that main advice classes are prioritized. ```bash if [[ -n "$MAIN_ADVICE_CLASSPATH" ]]; then CLASSPATH="${MAIN_ADVICE_CLASSPATH}:${CLASSPATH}" fi ``` -------------------------------- ### Conditional logic based on Bazel features Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Shows how to use Bazel features to conditionally adjust rule implementation logic, such as using a newer launcher configuration if available. ```starlark load("@bazel_features//:features.bzl", "bazel_features") def _rule_impl(ctx): if bazel_features.rules._has_launcher_maker_toolchain: # Use newer launcher configuration pass else: # Fall back to older approach pass ``` -------------------------------- ### Build Deploy JAR Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_binary.md Explicitly build the deploy JAR for distribution. This JAR contains all transitive dependencies merged into a single archive. ```bash bazel build //path/to:target_deploy.jar ``` -------------------------------- ### Building a Classpath String from JavaInfo Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md This utility function takes a list of JavaInfo providers and constructs a classpath string by aggregating all transitive runtime JARs. It's useful for tools or actions that require a flattened classpath. ```starlark def _build_classpath(java_infos): all_jars = depset(transitive=[ info.transitive_runtime_jars for info in java_infos ]) return ":".join([jar.path for jar in all_jars.to_list()]) ``` -------------------------------- ### Performance tuning: Starlark profiling Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Enables Starlark profiling to analyze build performance. ```bash # Enable Starlark profiling --profile=profile.json ``` -------------------------------- ### Integrating with rules_jvm_external Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_import.md Shows how to use `maven_install` from rules_jvm_external to fetch Maven artifacts and automatically generate java_import targets. This is the standard way to manage external Java dependencies in Bazel. ```python # MODULE.bazel or WORKSPACE load(@rules_jvm_external//:defs.bzl, maven_install) maven_install( artifacts = [ "com.google.guava:guava:31.1-jre", "org.log4j:log4j-api:2.20.0", ], repositories = [ "https://repo1.maven.org/maven2", ], ) ``` -------------------------------- ### java_test with Configuration and Resources Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_test.md Configures a `java_test` for integration testing with specific JVM flags, size, and timeout settings. It includes dependencies on integration libraries and testing utilities. ```starlark java_test( name = "integration_test", srcs = ["IntegrationTest.java"], test_class = "com.example.IntegrationTest", size = "large", timeout = "long", jvm_flags = [ "-Xmx4G", "-Dtest.mode=integration", ], deps = [ ":integration_lib", ":test_fixtures", "@maven//:junit_junit", "@maven//:com_google_truth_truth", ], ) ``` -------------------------------- ### Registering Toolchains in WORKSPACE Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_toolchain.md Registers multiple Java toolchains for Bazel to select from based on project needs. ```python # WORKSPACE or MODULE.bazel register_toolchains( "//toolchains:java11_toolchain", "//toolchains:java17_strict_toolchain", ) ``` -------------------------------- ### Debugging: Print timing information Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Enables the printing of timing information for build actions. ```bash # Print timing information --profile=profile.json ``` -------------------------------- ### Basic http_jar Usage in MODULE.bazel Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Defines a repository rule to download a single JAR file using its URL and SHA-256 checksum. This is useful for including external libraries without a package manager. ```python load("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "junit_jar", urls = ["https://repo1.maven.org/maven2/junit/junit/4.13.2/junit-4.13.2.jar"], sha256 = "8e495b634469d64fb8acfa3495a065cdc1d38dda7eccda76921b8b9f31f9cc81", ) ``` -------------------------------- ### http_jar with Custom BUILD File Content Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Downloads a JAR and defines its Bazel targets using inline BUILD file content. This allows customization of how the downloaded JAR is exposed. ```python http_jar( name = "custom_lib", urls = ["https://example.com/custom.jar"], sha256 = "abcd1234...", build_file_content = """ java_import( name = "lib", jars = ["custom.jar"], visibility = ["//visibility:public"], ) """, ) ``` -------------------------------- ### Performance tuning: Disk cache Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Enables caching of build outputs to disk. ```bash # Cache build outputs --disk_cache= ``` -------------------------------- ### Define Java Runtime with Platform Constraints Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_runtime.md Use the `java_runtime` rule to specify a Java runtime and its compatible platforms. This ensures the runtime is only selected on systems matching the defined `target_compatible_with` constraints. ```starlark java_runtime( name = "openjdk11_linux_aarch64", java_home = "@openjdk11_aarch64//:jdk", version = 11, target_compatible_with = [ "@platforms//os:linux", "@platforms//cpu:aarch64", ], ) ``` -------------------------------- ### http_jar with Multiple URLs and SHA256 Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/http_jar.md Imports a JAR file, providing a primary URL and a mirror URL for redundancy. The SHA-256 checksum ensures the integrity of the downloaded file. ```python load("@rules_java//java:http_jar.bzl", "http_jar") http_jar( name = "guava", urls = [ "https://repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar", "https://mirror.bazel.build/repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar", ], sha256 = "119ea2b9f3f63b78de4458333ba4e8ecbb06a37c02ea371835621f238e3ee46e", ) ``` -------------------------------- ### BootClassPathInfo Provider Definition Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/types-reference.md Defines the BootClassPathInfo provider for boot classpath configuration. This is an advanced type, rarely used directly, and includes boot classpath entries and system module files. ```starlark BootClassPathInfo = provider( doc = "Boot classpath information", fields = { "bootclasspath": "Boot classpath entries", "system_modules": "System module files", }, ) ``` -------------------------------- ### Debugging: Show all executed commands Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Configures Bazel to display all executed commands during the build. ```bash # Show all executed commands --subcommands ``` -------------------------------- ### Load Core Java Rules Source: https://github.com/bazelbuild/rules_java/blob/master/README.md Add this load statement to your BUILD or .bzl files to use the core Java rules provided by rules_java. ```build load(@rules_java//java:java_library.bzl, "java_library") ``` -------------------------------- ### Register Java Toolchains in MODULE.bazel Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/configuration-reference.md Register custom Java toolchains and JDKs using java_repository and register_toolchains in the MODULE.bazel file. ```python # Register Java toolchains load(@rules_java//java:extensions.bzl", "java_repository") java_repository( name = "my_jdk", version = 17, java_home = "/usr/lib/jvm/java-17-openjdk", ) register_toolchains("//toolchains:java17") ``` -------------------------------- ### Exporting Transitive Dependencies with JavaInfo Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-info-provider.md Shows how to construct a `JavaInfo` provider, specifically setting the `exports` field to re-export transitive dependencies. This is useful for aggregating dependencies from multiple sources. ```starlark java_info = JavaInfo( output_jar = output_jar, compile_jar = output_jar, exports = depset(transitive=[ dep[JavaInfo].exports for dep in ctx.attr.exports if JavaInfo in dep ]), # ... other fields ) ``` -------------------------------- ### Load java_toolchain Rule Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_toolchain.md Load the java_toolchain rule definition from its Starlark file. ```starlark load("@rules_java//java/toolchains:java_toolchain.bzl", "java_toolchain") ``` -------------------------------- ### Integrate java_runtime in java_toolchain Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_runtime.md Shows how to associate a defined `java_runtime` with a `java_toolchain` rule. This links the specific JDK/JRE to the toolchain configuration. ```starlark java_toolchain( name = "java11", # ... other attributes ... java_runtime = ":local_jdk", ) ``` -------------------------------- ### Integrate Package Configurations into java_toolchain Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_package_configuration.md Applies defined package configurations to a Java toolchain. This allows the toolchain to use the specified compiler options for different packages. ```starlark java_toolchain( name = "configured_toolchain", javacopts = ["-encoding", "UTF-8"], package_configurations = [ ":api_strict", ":legacy_lenient", ], # ... other toolchain attributes ... ) ``` -------------------------------- ### java_import with Dependencies Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_import.md Import a JAR and specify its direct dependencies. These dependencies will be added to the runtime classpath. ```starlark java_import( name = "spring_core", jars = ["spring-core-6.0.0.jar"], deps = [ ":spring_jcl", ], ) java_import( name = "spring_jcl", jars = ["spring-jcl-6.0.0.jar"], ) ``` -------------------------------- ### Load java_common Module Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-common.md Import the java_common module to access its utility functions. ```starlark load("@rules_java//java:defs.bzl", "java_common") ``` -------------------------------- ### Applying Java Plugins with java_common.compile Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java-plugin-info.md This snippet shows how to pass Java plugins to the `java_common.compile()` function. Ensure that `JavaPluginInfo` is correctly extracted from the plugin attributes. ```starlark result = java_common.compile( ctx, source_jars = ctx.files.srcs, output = output_jar, plugins = [info[JavaPluginInfo] for info in ctx.attr.plugins], java_toolchain = java_toolchain, ) ``` -------------------------------- ### Provider Type Checking with 'in' Operator Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/types-reference.md Demonstrates how to use the 'in' operator to verify the presence of a provider like JavaInfo on a target. ```starlark if JavaInfo in target: java_info = target[JavaInfo] ``` -------------------------------- ### Load java_runtime Rule Source: https://github.com/bazelbuild/rules_java/blob/master/_autodocs/java_runtime.md This is the standard directive to load the `java_runtime` rule definition from its Bazel BUILD file. ```starlark load("@rules_java//java/toolchains:java_runtime.bzl", "java_runtime") ```