1. Overview
1.概述
This tutorial provides a practical guide on how to build a Java-based project using Gradle.
本教程提供了一个实用指南,说明如何使用Gradle构建一个基于Java的项目。
We’ll explain the steps of manually creating a project structure, performing the initial configuration, and adding the Java plug-in and JUnit dependency. Then, we’ll build and run the application.
我们将解释手动创建项目结构、执行初始配置以及添加Java插件和JUnit依赖的步骤。然后,我们将构建并运行该应用程序。
Finally, in the last section, we’ll give an example of how to do this with the Gradle Build Init Plugin. Some basic introduction can be also found in the article Introduction to Gradle.
最后,在最后一节中,我们将举例说明如何使用Gradle Build Init插件来实现。一些基本的介绍也可以在Introduction to Gradle这篇文章中找到。
2. Java Project Structure
2.Java项目结构
Before we manually create a Java project and prepare it for build, we need to install Gradle.
在我们手动创建一个Java项目并准备构建它之前,我们需要安装Gradle。
Let’s start creating a project folder using the PowerShell console with name gradle-employee-app:
让我们开始使用PowerShell控制台创建一个项目文件夹,名称为gradle-employee-app。
> mkdir gradle-employee-app
After that, let’s navigate to the project folder and create sub-folders:
之后,让我们导航到项目文件夹并创建子文件夹。
> mkdir src/main/java/employee
The resulting output is shown:
由此产生的输出结果显示。
Directory: D:\gradle-employee-app\src\main\java
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 4/10/2020 12:14 PM employee
Within the project structure above, let’s create two classes. One is a simple Employee class with data such as name, email address, and year of birth:
在上面的项目结构中,让我们创建两个类。一个是简单的Employee类,有姓名、电子邮件地址和出生年份等数据。
public class Employee {
String name;
String emailAddress;
int yearOfBirth;
}
The second is the main Employee App class that prints Employee data:
第二个是主要的Employee App类,用于打印Employee数据。
public class EmployeeApp {
public static void main(String[] args){
Employee employee = new Employee();
employee.name = "John";
employee.emailAddress = "john@baeldung.com";
employee.yearOfBirth = 1978;
System.out.println("Name: " + employee.name);
System.out.println("Email Address: " + employee.emailAddress);
System.out.println("Year Of Birth:" + employee.yearOfBirth);
}
}
3. Build a Java Project
3.建立一个Java项目
Next, to build our Java project, we create a build.gradle configuration file in the project root folder.
接下来,为了构建我们的Java项目,我们在项目根目录下创建一个build.gradle配置文件。
The following is in the PowerShell command-line:
以下是PowerShell命令行中的内容。
Echo > build.gradle
We skip the next step related to the input parameters:
我们跳过与输入参数有关的下一个步骤。
cmdlet Write-Output at command pipeline position 1
Supply values for the following parameters:
InputObject[0]:
For a build to be successful, we need to add the Application Plugin:
为了使构建成功,我们需要添加应用插件。
plugins {
id 'application'
}
Then, we apply an application plugin and add a fully-qualified name of the main class:
然后,我们应用一个应用程序插件,并添加一个完全限定的主类名称:。
apply plugin: 'application'
mainClassName = 'employee.EmployeeApp'
Each project consists of tasks. A task represents a piece of work that a build performs such as compiling the source code.
每个项目由tasks组成。一个任务代表构建所执行的一项工作,如编译源代码。
For instance, we can add a task to the configuration file that prints a message about the completed project configuration:
例如,我们可以在配置文件中添加一个任务,打印出一条关于完成项目配置的消息。
println 'This is executed during configuration phase'
task configured {
println 'The project is configured'
}
Usually, gradle build is the primary task and the one most used. This task compiles, tests, and assembles the code into a JAR file. The build is started by typing:
通常情况下,gradle build是主要任务,也是使用最多的任务。这个任务对代码进行编译、测试,并将其组装成一个JAR文件。构建工作是通过键入以下内容开始的。
> gradle build
Execute the command above to output:
执行上面的命令来输出。
> Configure project :
This is executed during configuration phase
The project is configured
BUILD SUCCESSFUL in 1s
2 actionable tasks: 2 up-to-date
To see the build results, let’s look at the build folder which contains sub-folders: classes, distributions, libs, and reports. Typing the Tree / F gives the structure of the build folder:
为了查看构建结果,让我们看看构建文件夹,该文件夹包含子文件夹: 类、分发、libs和报告。输入Tree / F就可以看到构建文件夹的结构。
├───build
│ ├───classes
│ │ └───java
│ │ ├───main
│ │ │ └───employee
│ │ │ Employee.class
│ │ │ EmployeeApp.class
│ │ │
│ │ └───test
│ │ └───employee
│ │ EmployeeAppTest.class
│ │
│ ├───distributions
│ │ gradle-employee-app.tar
│ │ gradle-employee-app.zip
│ ├───libs
│ │ gradle-employee-app.jar
│ │
│ ├───reports
│ │ └───tests
│ │ └───test
│ │ │ index.html
│ │ │
│ │ ├───classes
│ │ │ employee.EmployeeAppTest.html
As you can see, the classes sub-folder contains two compiled .class files we previously created. The distributions sub-folder contains an archived version of the application jar package. And libs keeps the jar file of our application.
正如你所看到的,classes子文件夹包含我们之前创建的两个已编译的.class文件。distributions子文件夹包含一个存档的应用程序jar包。而libs保存着我们应用程序的jar文件。
Usually, in reports, there are files that are generated when running JUnit tests.
通常情况下,i在报告中,有一些文件是在运行JUnit测试时产生的。
Now everything is ready to run the Java project by typing gradle run.The result of executing the application on exit:
现在一切准备就绪,可以通过输入gradle run.退出时执行应用程序的结果:
> Configure project :
This is executed during configuration phase
The project is configured
> Task :run
Name: John
Email Address: john@baeldung.com
Year Of Birth:1978
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
3.1. Build Using Gradle Wrapper
3.1.使用Gradle Wrapper构建
The Gradle Wrapper is a script that invokes a declared version of Gradle.
Gradle Wrapper是一个调用Gradle声明版本的脚本。
First, let’s define a wrapper task in the build.gradle file:
首先,让我们在build.gradle文件中定义一个包装任务。
task wrapper(type: Wrapper){
gradleVersion = '5.3.1'
}
Let’s run this task using gradle wrapper from Power Shell:
让我们使用Power Shell的gradle wrapper来运行这个任务。
> Configure project :
This is executed during configuration phase
The project is configured
BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
Several files will be created under the project folder, including the files under /gradle/wrapper location:
在项目文件夹下将创建几个文件,包括/gradle/wrapper位置下的文件。
│ gradlew
│ gradlew.bat
│
├───gradle
│ └───wrapper
│ gradle-wrapper.jar
│ gradle-wrapper.properties
- gradlew: the shell script used to create Gradle tasks on Linux
- gradlew.bat: a .bat script that Windows users to create Gradle tasks
- gradle-wrapper.jar: a wrapper-executable jar of our application
- gradle-wrapper.properties: properties file for configuring the wrapper
4. Add Java Dependencies and Run a Simple Test
4.添加Java依赖性并运行一个简单的测试
First, in our configuration file, we need to set a remote repository from where we download dependency jars. Most often, these repositories are either mavenCentral() or jcenter(). Let’s choose the second one:
首先,在我们的配置文件中,我们需要设置一个远程仓库,从那里下载依赖性jar。大多数情况下,这些仓库是mavenCentral()或jcenter()。让我们选择第二个。
repositories {
jcenter()
}
With our repositories created, we can then specify which dependencies to download. In this example, we are adding Apache Commons and JUnit library. To implement, add testImplementation and testRuntime parts in the dependencies configuration.
在创建了我们的资源库后,我们可以指定下载哪些依赖项。在这个例子中,我们要添加Apache Commons和JUnit库。为了实现,在依赖项配置中添加testImplementation和testRuntime部分。
It builds on an additional test block:
它建立在一个额外的测试块上。
dependencies {
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
testImplementation('junit:junit:4.13')
testRuntime('junit:junit:4.13')
}
test {
useJUnit()
}
When that’s done, let’s try the work of JUnit on a simple test. Navigate to the src folder and make the sub-folders for the test:
当这些完成后,让我们在一个简单的测试上试试JUnit的工作。导航到src文件夹,为测试做子文件夹。
src> mkdir test/java/employee
Within the last sub-folder, let’s create EmployeeAppTest.java:
在最后一个子文件夹中,让我们创建EmployeeAppTest.java。
public class EmployeeAppTest {
@Test
public void testData() {
Employee testEmp = this.getEmployeeTest();
assertEquals(testEmp.name, "John");
assertEquals(testEmp.emailAddress, "john@baeldung.com");
assertEquals(testEmp.yearOfBirth, 1978);
}
private Employee getEmployeeTest() {
Employee employee = new Employee();
employee.name = "John";
employee.emailAddress = "john@baeldung.com";
employee.yearOfBirth = 1978;
return employee;
}
}
Similar to before, let’s run a gradle clean test from the command line and the test should pass without issue.
与之前类似,让我们从命令行中运行一个gradle clean test,测试应该没有问题。
5. Java Project Initialization Using Gradle
5.使用Gradle进行Java项目初始化
In this section, we’ll explain the steps for creating and building a Java application that we have gone through so far. The difference is that this time, we work with the help of the Gradle Build Init Plugin.
在本节中,我们将解释到目前为止所经历的创建和构建一个Java应用程序的步骤。不同的是,这一次,我们在Gradle Build Init插件的帮助下工作。
Create a new project folder and name it gradle-java-example. Then, switch to that empty project folder and run the init script:
创建一个新的项目文件夹并命名为gradle-java-example.然后,切换到该空项目文件夹并运行init脚本。
> gradle init
Gradle will ask us with few questions and offer options for creating a project. The first question is what type of project we want to generate:
Gradle会问我们几个问题并提供创建项目的选项。第一个问题是我们想生成什么类型的项目。
Select type of project to generate:
1: basic
2: cpp-application
3: cpp-library
4: groovy-application
5: groovy-library
6: java-application
7: java-library
8: kotlin-application
9: kotlin-library
10: scala-library
Select build script DSL:
1: groovy
2: kotlin
Enter selection [1..10] 6
Select option 6 for the type of project and then first option (groovy) for the build script.
项目类型选择选项6,然后构建脚本选择第一个选项(groovy)。
Next, a list of questions appears:
接下来,出现了一个问题清单。
Select test framework:
1: junit
2: testng
3: spock
Enter selection (default: junit) [1..3] 1
Project name (default: gradle-java-example):
Source package (default: gradle.java.example): employee
BUILD SUCCESSFUL in 57m 45s
2 actionable tasks: 2 executed
Here, we select the first option, junit, for the test framework. Select the default name for our project and type “employee” as the name of the source package.
在这里,我们选择第一个选项,junit,作为测试框架。为我们的项目选择默认名称,并输入 “雇员 “作为源包的名称。
To see the complete directory structure within /src project folders, let’s type Tree /F in Power Shell:
为了查看/src项目文件夹内的完整目录结构,让我们在Power Shell中输入Tree /F 。
├───main
│ ├───java
│ │ └───employee
│ │ App.java
│ │
│ └───resources
└───test
├───java
│ └───employee
│ AppTest.java
│
└───resources
Finally, if we build the project with gradle run, we get “Hello World” on exit:
最后,如果我们用gradle run构建项目,我们在退出时得到“Hello World”。
> Task :run
Hello world.
BUILD SUCCESSFUL in 1s
2 actionable tasks: 1 executed, 1 up-to-date
6. Conclusion
6.结语
In this article, we’ve presented two ways to create and build a Java application using Gradle. The fact is, we did the manual work and it took time to start compiling and building applications from the command line. In this case, we should pay attention to the import of some required packages and classes if the application uses multiple libraries.
在这篇文章中,我们介绍了使用Gradle创建和构建Java应用程序的两种方法。事实是,我们做的是手工作业,从命令行开始编译和构建应用程序需要时间。在这种情况下,如果应用程序使用多个库,我们应该注意导入一些必要的包和类。
On the other side, the Gradle init script has features that generate a light skeleton of our project, as well as some of the configuration files associated with Gradle.
在另一边,Gradle init脚本的功能是生成我们项目的轻量级骨架,以及一些与Gradle相关的配置文件。
The source code for this article is available over on GitHub.
本文的源代码可在GitHub上获得。