Learn Gradle-ch 3 Java QuickStart

Source: Internet
Author: User
Tags maven central

Previous chapter ( links we mainly introduce the script of Gradle, this chapter we will continue to learn another feature of Gradle-plug-in (plugins).

1, plug-in introduction

Plugins are extensions to the Gradle feature, and Gradle has a rich plugin where you can search for relevant plugins ( portals ). This chapter provides a brief introduction to Gradle's Java plugin (Java plugin), which adds tasks to your build project, such as compiling Java classes, performing unit tests, and packaging compiled class files into jar files.

The Java plug-in is a contract-based (contract-better than configuration), which defines default values in many aspects of the project, such as where the Java source files should be located. As long as we follow the plugin's conventions, we do not need to make additional related configuration in the Gradle configuration script. Of course, in some cases, it is also possible for your project to not want or fail to follow this convention, so you will need to configure your build scripts in additional.

The Gradle Java plugin is similar to MAVEN for the default location of project files.

Java source code stored in directory: Src/main/java

Java Test Code storage directory: Src/test/java

Resource File storage directory: Src/main/resources

Test related resource File storage directory: Src/test/resources

All output files are in directory: Build

The output jar file is located in the directory: Build/libs

2. A simple Java project

Create a new file Build.gradle, add code:

Apply plugin: ' java '

The above code configures the Java plug-in into the build script. When you execute a build script, it adds a series of tasks to the project. We do: Gradle build to see the results of the output:

: Compilejava up-to-date:processresources up-to-date:classes up-to-date:jar up-to-date:assemble UP-TO-DATE: Compiletestjava up-to-date:processtestresources up-to-date:testclasses up-to-date:test UP-TO-DATE:check UP-TO-DATE: Build Up-to-datebuild Successful

As you can see from the output, the build that we perform relies on other tasks, such as Compilejava, which is a predefined set of tasks for the Java plugin.

You can also perform a number of other tasks, such as executing: Gradle clean,gradle assemble,gradle Check, and so on.

Gradle Clean: Delete The build directory and the files that have been built;

Gradle Assemble (assembly): Compiles and packages Java code, but does not perform unit tests (as can be seen from the task dependency results above). If you apply a different plugin, you will also complete other actions. For example, if you apply a war plugin, the task will generate a war file for your project.

Gradle check: Compile and execute the test. Similar to assemble, if you apply other plugins that include a check task, such as the Checkstyle plugin, this task will check the quality of your project code and generate a test report.

: Tasks------------------------------------------------------------all tasks runnable from  Root project------------------------------------------------------------build  Tasks-----------Assemble - assembles the outputs of this project.build  - Assembles and tests this project.buildDependents - Assembles  and tests this project and all projects that depend on  it.buildneeded - assembles and tests this project and all  projects it depends on.classes - assembles classes  ' main '. clean -  Deletes the build directory.jar - Assembles a jar archive  containing the main classes.testclasses - assembles classes  ' Test '. Build setup tasks-----------------Init - iniTializes a new gradle build. [incubating]wrapper - generates gradle  wrapper files. [incubating]documentation tasks-------------------javadoc -  Generates javadoc api documentation for the main source code. Help tasks----------components - displays the components produced by  root project  ' Learn-gradle ' . [incubating]dependencies - displays all  dependencies declared in root project  ' Learn-gradle '                                                                                                            . Dependencyinsight - displays the insight into a specific dependency  in root project  ' Learn-gradle ' .help - displays a help  message.model - displays the configuration model of root project  ' Learn-gradle '.  [incubating]projects - displays the sub-projects of root  project  ' Learn-gradle '. Properties - displays the properties of root  project  ' Learn-gradle ' .tasks - displays the tasks runnable from  root project  ' Learn-gradle '. Verification tasks------------------Check - runs all checks.test - rUns the unit tests. Rules-----Pattern: clean<taskname>: cleans the output files of a  task. pattern: build<configurationname>: assembles the artifacts of a  Configuration. Pattern: upload<configurationname>: assembles and uploads the artifacts  belonging to a configuration. To see all tasks and more detail, run gradle tasks --allto  see more detail about a task, run gradle help --task  <task>build successful

Do the small partners see if there is any doubt as to what happens if a task named tasks is defined in the build script? A curious little companion can try it on his own. In fact, it will cover the original task.

3. External dependence

Typically a Java project relies on multiple other projects or jar files, and we can configure the Gradle warehouse (repository) to tell Gradle where to get the required dependencies, and Gradle can also be configured to use the MAVEN repository. For example, we configured Gradle to use the MAVEN central repository in build. Add code in gradle :

repositories {mavencentral ()}

Next, let's add some dependencies. code example:

dependencies {Compile group: ' Commons-collections ', Name: ' Commons-collections ', Version: ' 3.2 ' Testcompile group: ' JUnit ', Name: ' JUnit ', version: ' 4.+ '}

On dependence, for the time being dot so much. You can refer to the Gradle Dependency Management Foundation in detail, or follow-up articles.

4. Define Project Properties

The Java plug-in adds a series of properties to the project, and usually the initial Java project is sufficient to use these default configurations, and we do not need to do any additional configuration. However, if the default property is not satisfied with your project, you can also make some information about customizing the project. For example, we specify the version number and some jar manifest information for the project.

sourcecompatibility = 1.5version = ' 1.0 ' jar {manifest {attributes ' Implementation-title ': ' Gradle Quickstart ', ' Implementation-version ': Version}}

In fact, the series of tasks added by the Java plug-in is no different from the task we previously customized in the script, which is a very regular task. We are free to customize and modify these tasks. For example, set properties for tasks, add behaviors to tasks, change dependencies on tasks, and even replace existing tasks. For example, we can configure a test task of type test to add a system property when the test task executes. The configuration script is as follows:

Test {systemproperties ' property ': ' Value '}

In addition, with the "Gradle Tasks" command type mentioned earlier, we can use "Gradle properties" to see what configurable properties are supported by the current configuration.

5. Publish the jar file to the warehouse
Uploadarchives {repositories {flatdir {dirs ' Repos '}}}

Executing the Gradle uploadarchives will publish the associated jar file to the Reops repository. For more information: publishing artifacts

6. Build multiple Java Projects

Let's say our project structure is as follows:

multiproject/--api/--services/webservice/--shared/--services/shared/

The project API generates the jar file, and the Java client accesses the Web service through the interface provided by the JAR; Project services/WebService is a webapp that provides Web services; project shared Contains API and webservice common code; Project services/shared relies on shared project, including WebService common code.

Next, we start defining multi-project builds.

1) First, we need to add a configuration file: Settings.gradle file. Settings.gradle is located at the root of the project, which is the Multiproject directory. To edit the Settings.gradle, enter the configuration information:

Include "Shared", "API", "Services:webservice", "services:shared"

Include is the settings method for Gradle the core type of the DSL definition , which is used to build the specified project. The parameters specified in the configuration, shared, API, and so on, default to the directory name of the current configuration directory, and "Services:webservice" maps the system physical path "Services/webservice" according to the default convention (relative to the root directory). For more detailed information on include, refer to: Build tree.

2) Define all child project public configurations. In the root directory, create the file: Build.gradle, enter the configuration information:

subprojects {Apply plugin: ' java ' Apply plugin: ' ECLIPSE-WTP ' repositories {mavencentral ()} Depend encies {testcompile ' junit:junit:4.12 '} Version = ' 1.0 ' jar {manifest.attributes provider: ' Grad Le '}}

Subprojects is one of the build script modules of the Gradle DSL definition that defines the configuration information for all child projects. In the above configuration, we defined the use of "Java" and "ECLIPSE-WTP" plug-ins for all sub-projects, and also defined warehouses, dependencies, version numbers, and jars (Jar is one of the Gradle task types, the task is to assemble the jar package, the JAR task contains the property manifest, The information used to describe the jar, specifically: jar).

We execute the gradle build command in the root directory, and these configurations are applied to all child projects.

3) Add dependencies to the project

New file: Api/build.gradle, add configuration:

dependencies {Compile project (': Shared ')}

Above, we define an API project that relies on a shared project , and when we execute the gradle build command in the root directory, Gradle ensures that the shared project compiles before compiling the API project before compiling the API.

Similarly, add Services/webservice/build.gradle, add configuration:

dependencies {Compile project (': Services:shared ')}

In the root directory execution: Gradle Compilejava, Output:

: Shared:compilejava up-to-date:shared:processresources up-to-date:shared:classes UP-TO-DATE:shared:jar UP-TO-DATE: Api:compilejava Up-to-date:services:compilejava Up-to-date:services:shared:compilejava UP-TO-DATE:services:shared :p rocessresources up-to-date:services:shared:classes Up-to-date:services:shared:jar UP-TO-DATE:services: Webservice:compilejava Up-to-datebuild Successful

By outputting the information we can clearly see whether the dependency configuration is correct. This is the end of the tutorial.

This article is my beginner gradle made notes, is in the side of learning gradle writing, if errors and omissions, but also please do not spray. I am not very grateful if I can point out the friendship and make progress together .

Learn Gradle-ch 3 Java QuickStart

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.