GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||
GeezerVison is showing docs.gradle.org — Building Java & JVM projects Building Java & JVM projects
version 9.9.3
On this Page
Gradle uses a convention-over-configuration approach to building JVM-based projects that borrows several conventions from Apache Maven. In particular, it uses the same default directory structure for source files and resources, and it works with Maven-compatible repositories. We will look at Java projects in detail in this chapter, but most of the topics apply to other supported JVM languages as well, such as Kotlin, Groovy and Scala.
IntroductionThe simplest build script for a Java project applies the Java Library Plugin and optionally sets the project version and selects the Java toolchain to use: build.gradle.kts
build.gradle
By applying the Java Library Plugin, you get a whole host of features:
This isn’t sufficient to build any non-trivial Java project — at the very least, you’ll probably have some file dependencies. But it means that your build script only needs the information that is specific to your project.
The Java Library Plugin also integrates the above tasks into the standard Base Plugin lifecycle tasks:
The rest of the chapter explains the different avenues for customizing the build to your requirements. You will also see later how to adjust the build for libraries, applications, web apps and enterprise apps. Declaring your source files via source setsGradle’s Java support was the first to introduce a new concept for building source-based projects: source sets. The main idea is that source files and resources are often logically grouped by type, such as application code, unit tests and integration tests. Each logical group typically has its own sets of file dependencies, classpaths, and more. Significantly, the files that form a source set don’t have to be located in the same directory! Source sets are a powerful concept that tie together several aspects of compilation:
You can see how these relate to one another in this diagram:
Figure 1. Source sets and Java compilation
The shaded boxes represent properties of the source set itself.
On top of that, the Java Library Plugin automatically creates a compilation task for every source set you or a plugin defines — named The
main source setMost language plugins, Java included, automatically create a source set called Java projects typically include resources other than source files, such as properties files, that may need processing — for example by replacing tokens within the files — and packaging within the final JAR.
The Java Library Plugin handles this by automatically creating a dedicated task for each defined source set called
Figure 2. Processing non-source files for a source set
As before, the shaded boxes represent properties of the source set, which in this case comprises the locations of the resource files and where they are copied to. In addition to the Projects typically use this source set for unit tests, but you can also use it for integration, acceptance and other types of test if you wish. The alternative approach is to define a new source set for each of your other test types, which is typically done for one or both of the following reasons:
You can see an example of this approach in the Java testing chapter, which shows you how to set up integration tests in a project. You’ll learn more about source sets and the features they provide in: Source set configurationsWhen a source set is created, it also creates a number of configurations as described above. Build logic should not attempt to create or access these configurations until they are first created by the source set. When creating a source set, if one of these automatically created configurations already exists, and its role is different than the role that the source set would have assigned, the build will fail. The build below demonstrates this behavior. build.gradle.kts
build.gradle
In this case, the build will fail. Following two simple best practices will avoid this problem:
Remember that any time you reference a configuration within the build.gradle
Managing your dependenciesThe vast majority of Java projects rely on libraries, so managing a project’s dependencies is an important part of building a Java project. Dependency management is a big topic, so we will focus on the basics for Java projects here. If you’d like to dive into the detail, check out the introduction to dependency management. Specifying the dependencies for your Java project requires just three pieces of information:
The first two are specified in a build.gradle.kts
build.gradle
The Gradle terminology for the three elements is as follows:
As far as configurations go, the main ones of interest are:
You can learn more about these and how they relate to one another in the plugin reference chapter. Be aware that the Java Library Plugin offers two additional configurations — Why no
compile configuration?The Java Library Plugin has historically used the We have only scratched the surface here, so we recommend that you read the dedicated dependency management chapters once you’re comfortable with the basics of building Java projects with Gradle. Some common scenarios that require further reading include:
You’ll discover that Gradle has a rich API for working with dependencies — one that takes time to master, but is straightforward to use for common scenarios. Compiling your codeCompiling both your production and test code can be trivially easy if you follow the conventions:
Other JVM language plugins, such as the one for Groovy, follow the same pattern of conventions. We recommend that you follow these conventions wherever possible, but you don’t have to. There are several options for customization, as you’ll see next. Customizing file and directory locationsImagine you have a legacy project that uses an src directory for the production code and test for the test code. The conventional directory structure won’t work, so you need to tell Gradle where to find the source files. You do that via source set configuration. Each source set defines where its source code resides, along with the resources and the output directory for the class files. You can override the convention values by using the following syntax: build.gradle.kts
build.gradle
Now Gradle will only search directly in src and test for the respective source code. What if you don’t want to override the convention, but simply want to add an extra source directory, perhaps one that contains some third-party source code you want to keep separate? The syntax is similar: build.gradle.kts
build.gradle
Crucially, we’re using the method You can see all the properties and methods available on source sets in the DSL reference for SourceSet and SourceDirectorySet. Note that Changing compiler optionsMost of the compiler options are accessible through the corresponding task, such as For example, if you want to use a separate JVM process for the compiler and prevent compilation failures from failing the build, you can use this configuration: build.gradle.kts
build.gradle
That’s also how you can change the verbosity of the compiler, disable debug output in the byte code and configure where the compiler can find annotation processors. Targeting a specific Java versionBy default, Gradle will compile Java code to the language level of the JVM running Gradle. If you need to target a specific version of Java when compiling, Gradle provides multiple options:
Using toolchainsWhen Java code is compiled using a specific toolchain, the actual compilation is carried out by a compiler of the specified Java version. The compiler provides access to the language features and JDK APIs for the requested Java language version. In the simplest case, the toolchain can be configured for a project using the build.gradle.kts
build.gradle
You can learn more about this in the Java toolchains guide. Using Java release versionSetting the release flag ensures the specified language level is used regardless of which compiler actually performs the compilation. To use this feature, the compiler must support the requested release version. It is possible to specify an earlier release version while compiling with a more recent toolchain. Gradle supports using the release flag from Java 10. It can be configured on the compilation task as follows. build.gradle.kts
build.gradle
The release flag provides guarantees similar to toolchains. It validates that the Java sources are not using language features introduced in later Java versions, and also that the code does not access APIs from more recent JDKs. The bytecode produced by the compiler also corresponds to the requested Java version, meaning that the compiled code cannot be executed on older JVMs. The Using Java compatibility options
The
These options can be set per JavaCompile task, or on the Targeting Java 6 and Java 7Gradle itself can only run on a JVM with Java version 8 or higher. However, Gradle still supports compiling, testing, generating Javadocs and executing applications for Java 6 and Java 7. Java 5 and below are not supported.
To use Java 6 or Java 7, the following tasks need to be configured:
With the usage of Java toolchains, this can be done as follows: build.gradle.kts
build.gradle
The only requirement is that Java 7 is installed and has to be either in a location Gradle can detect automatically or explicitly configured. Compiling independent sources separatelyMost projects have at least two independent sets of sources: the production code and the test code. Gradle already makes this scenario part of its Java convention, but what if you have other sets of sources? One of the most common scenarios is when you have separate integration tests of some form or other. In that case, a custom source set may be just what you need. You can see a complete example for setting up integration tests in the Java testing chapter. You can set up other source sets that fulfil different roles in the same way. The question then becomes: when should you define a custom source set? To answer that question, consider whether the sources:
If your answer to both 3 and either one of the others is yes, then a custom source set is probably the right approach. For example, integration tests are typically part of the project because they test the code in Other common scenarios are less clear cut and may have better solutions. For example:
If you’re unsure whether to create a custom source set or not, then go ahead and do so. It should be straightforward and if it’s not, then it’s probably not the right tool for the job. Debugging compiling errorsGradle provides detailed reporting for compilation failures. If a compilation task fails, the summary of errors is displayed in the following locations:
This reporting feature works with the Managing resourcesMany Java projects make use of resources beyond source files, such as images, configuration files and localization data. Sometimes these files simply need to be packaged unchanged and sometimes they need to be processed as template files or in some other way. Either way, the Java Library Plugin adds a specific Copy task for each source set that handles the processing of its associated resources. The task’s name follows the convention of Since Java properties files and reproducible buildsYou can easily create Java properties files via the WriteProperties task, which fixes a well-known problem with The standard Java API for writing properties files produces a unique file every time, even when the same properties and values are used, because it includes a timestamp in the comments. Gradle’s
Sometimes it can be desirable to recreate archives in a byte for byte way on different machines. You want to be sure that building an artifact from source code produces the same result, byte for byte, no matter when and where it is built. This is necessary for projects like reproducible-builds.org. These tweaks not only lead to better incremental build integration, but they also help with reproducible builds. In essence, reproducible builds guarantee that you will see the same results from a build execution — including test results and production binaries — no matter when or on what system you run it. Running testsAlongside providing automatic compilation of unit tests in src/test/java, the Java Library Plugin has native support for running tests that use JUnit 3, 4 & 5 (JUnit 5 support came in Gradle 4.6) and TestNG. You get:
You do not get a As there is a lot to cover when it comes to testing, the topic has its own chapter in which we look at:
You can also learn more about configuring tests in the DSL reference for Test. Packaging and publishingHow you package and potentially publish your Java project depends on what type of project it is. Libraries, applications, web applications and enterprise applications all have differing requirements. In this section, we will focus on the bare bones provided by the Java Library Plugin. By default, the Java Library Plugin provides the build.gradle.kts
build.gradle
If you want to create an 'uber' (AKA 'fat') JAR, then you can use a task definition like this: build.gradle.kts
build.gradle
See Jar for more details on the configuration options available to you.
And note that you need to use You can use one of the publishing plugins to publish the JARs created by a Java project: Modifying the JAR manifestEach instance of the build.gradle.kts
build.gradle
Manifest attribute values can be provided lazily using the Provider API.
In the example above, build.gradle.kts
build.gradle
See Manifest for the configuration options it provides. You can also create standalone instances of build.gradle.kts
build.gradle
Another option available to you is to merge manifests into a single build.gradle.kts
build.gradle
Manifests are merged in the order they are declared in the Speaking of build.gradle.kts
build.gradle
Generating API documentationThe Java Library Plugin provides a As an example of what you can do, imagine you want to use Asciidoc syntax in your Javadoc comments. To do this, you need to add Asciidoclet to Javadoc’s doclet path. Here’s an example that does just that: build.gradle.kts
build.gradle
You don’t have to create a configuration for this, but it’s an elegant way to handle dependencies that are required for a unique purpose. You might also want to create your own Javadoc tasks, for example to generate API docs for the tests: build.gradle.kts
build.gradle
These are just two non-trivial but common customizations that you might come across. Cleaning the buildThe Java Library Plugin adds a Building JVM componentsAll of the specific JVM plugins are built on top of the Java Plugin. The examples above only illustrated concepts provided by this base plugin and shared with all JVM plugins. Read on to understand which plugins fits which project type, as it is recommended to pick a specific plugin instead of applying the Java Plugin directly. Building Java librariesThe unique aspect of library projects is that they are used (or "consumed") by other Java projects. That means the dependency metadata published with the JAR file — usually in the form of a Maven POM — is crucial. In particular, consumers of your library should be able to distinguish between two different types of dependencies: those that are only required to compile your library and those that are also required to compile the consumer. Gradle manages this distinction via the Java Library Plugin, which introduces an api configuration in addition to the implementation one covered in this chapter. If the types from a dependency appear in public fields or methods of your library’s public classes, then that dependency is exposed via your library’s public API and should therefore be added to the api configuration. Otherwise, the dependency is an internal implementation detail and should be added to implementation. If you’re unsure of the difference between an API and implementation dependency, the Java Library Plugin chapter has a detailed explanation. Building Java applicationsJava applications packaged as a JAR aren’t set up for easy launching from the command line or a desktop environment. The Application Plugin solves the command line aspect by creating a distribution that includes the production JAR, its dependencies and launch scripts Unix-like and Windows systems. See the plugin’s chapter for more details, but here’s a quick summary of what you get:
Building Java web applicationsJava web applications can be packaged and deployed in a number of ways depending on the technology you use. For example, you might use Spring Boot with a fat JAR or a Reactive-based system running on Netty. Whatever technology you use, Gradle and its large community of plugins will satisfy your needs. Core Gradle, though, only directly supports traditional Servlet-based web applications deployed as WAR files. That support comes via the War Plugin, which automatically applies the Java Plugin and adds an extra packaging step that does the following:
This is done by the There is no core support for running your web application directly from the build, but we do recommend that you try the Gretty community plugin, which provides an embedded Servlet container. Building Java EE applicationsJava enterprise systems have changed a lot over the years, but if you’re still deploying to JEE application servers, you can make use of the Ear Plugin. This adds conventions and a task for building EAR files. The plugin’s chapter has more details. Building Java PlatformsA Java platform represents a set of dependency declarations and constraints that form a cohesive unit to be applied on consuming projects. The platform has no source and no artifact of its own. It maps in the Maven world to a BOM. The support comes via the Java Platform plugin, which sets up the different configurations and publication components.
Enabling Java preview features
To enable Java preview features for compilation, test execution and runtime, you can use the following DSL snippet: build.gradle.kts
build.gradle
Building other JVM language projectsIf you want to leverage the multi language aspect of the JVM, most of what was described here will still apply. Gradle itself provides Groovy and Scala plugins.
The plugins automatically apply support for compiling Java code and can be further enhanced by combining them with the Compilation dependency between languagesThese plugins create a dependency between Groovy/Scala compilation and Java compilation (of source code in the build.gradle.kts
build.gradle
All of this is possible through the use of directory properties. Extra language supportBeyond core Gradle, there are other great plugins for more JVM languages! | ||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |