"Spring" Building Java Projects with Gradle__java

Source: Internet
Author: User
Tags local time wrapper version control system

Building Java Projects with Gradle

This guide walks your through using gradle to build a simple Java project.


1, what is the construction. -What ' ll build


' ll create a simple app and then build it using Gradle.


2. What is needed. -What you ' ll need


About minutes

A Favorite text editor or IDE

JDK 6 or later


3, how complete this guide-how to complete this guide


Like most Spring Getting Started guides, you can start with scratch and complete each step, or you can bypass basic setup Steps that are already familiar. Either way with working code.

To start in scratch, move on to Set up the project.

To Skip the basicsand do the following:

Download and unzip the source repository for this guide, or clone it usinggit:git CLONEHTTPS://GITHUB.COM/SPRING-GUIDES/GS -gradle.git

CD into Gs-gradle/initial

Jump ahead to Install Gradle.

When you ' re finished, you can check your results against the code ings-gradle/complete.


4, the establishment of the project-set up the project


The set up a Java project for Gradle to build. To keep the focus on Gradle and make the project as simple as possible for now. Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; For example, Withmkdir-p Src/main/java/hello on *nix systems:

(using commands under Windows: mkdir Src\main\java\hello)

└──SRC
    └──main
        └──java
            └──hello

Within The Src/main/java/hello directory, you can create any Java classes for you want. For simplicity ' s sake and for consistency with the rest of this guide, Spring recommends that you create two Classes:hello World.java Andgreeter.java.

Src/main/java/hello/helloworld.java

Package Hello;

public class HelloWorld {public
  static void Main (string[] args) {
    Greeter Greeter = new Greeter ();
    System.out.println (Greeter.sayhello ());
  }

Src/main/java/hello/greeter.java

Package Hello;

public class Greeter {public
  String SayHello () {return
    "Hello world!";
  }
}

5, installation Gradle-install Gradle

Now so you have a project this can build with Gradle, can install Gradle.

Gradle is downloadable as a zip file at http://www.gradle.org/downloads. Only the "binaries are required, so" for "link to gradle-version-bin.zip. (You can also choose Gradle-version-all.zip to get the sources and documentation as as.)

Unzip the file to your computer, and add the Bin folder to your path.

To test the Gradle installation, run Gradle from the command-line:

Gradle

If everything is OK, you will see the following welcome message:

: Help

Welcome to Gradle 2.1.

To run a build, run Gradle <task> ...

To a list of available tasks, run Gradle tasks

To a list of command-line options, run Gradle--help

Build successful

Total time:12.281 secs

By now, you have installed the Gradle.


6, Discover Gradle can do what-find out what gradle can do


Now, the Gradle is installed, the what it can do. Before you even create a build.gradle file for the project, your can ask it what tasks are available:

Gradle Tasks

You should a list of available tasks. Assuming you run gradle into a folder that doesn ' t already have abuild.gradle file, and you'll be here some very elementary tasks Su Ch as this:

: Tasks = All tasks runnable from root project = Build Setup tasks setupbuild-initializes a new gradle build. [incubating] wrapper-generates gradle wrapper files.
[incubating] = = Help tasks dependencies-displays all dependencies declared in root project ' Gs-gradle '.
Dependencyinsight-displays the insight into a specific dependency in root project ' Gs-gradle '.
Help-displays a Help message projects-displays the sub-projects of root project ' Gs-gradle '.
Properties-displays the properties of root project ' Gs-gradle '.

Tasks-displays the tasks runnable from root project ' Gs-gradle '.

To the All tasks and more detail, run with--all. Build successful total time:3.077 secs 

Even though these tasks are available, they don ' t offer much value without a project build configuration. As you flesh out Thebuild.gradle file, some tasks would be more useful. The list of tasks would grow as you add plugins tobuild.gradle and so I ll occasionally want to run tasks again to What tasks are available.

Speaking of adding plugins, next you add a plugin This enables basic Java build functionality.


7. Build Java code


Starting simple, create a very basic Build.gradle file this has only one line in it:

Apply plugin: ' java '

This configuration brings a significant amount to power. Rungradle Tasks again, and you are the new tasks added to the list, including tasks for building the project, Creatin G JavaDoc, and running tests.

You'll use the gradle build task frequently. This task compiles, tests, and assembles the code into a JAR file. Can run it like this:

Gradle Build

After a few seconds, "build successful" indicates this build has completed.

D:\Java\Spring\Guides\Building Java Projects with Gradle\gs-gradle>gradle build
: Compilejava
:p rocessresources Up-to-date
: Classes
: Jar
: Assemble
: Compiletestjava Up-to-date
:p rocesstestresources Up-to-date
: testclasses Up-to-date
: Test up-to-date
: Check Up-to-date
: Build

Build successful

Total time:11.39 secs

To the results of the "build" effort, take a look into the build folder. Therein you'll find several directories, including these three notable:

Classes. The project ' s compiled. class files.

Reports. Reports produced by the build (such as Test Reports).

Libs. Assembled project libraries (usually JAR and/or WAR files).

The classes folder has. class files that are generated from compiling the Java code. Specifically, should find Helloworld.class and Greeter.class.

At I, the project doesn ' t have any library dependencies, so there ' s nothing in thedependency_cache Folde R.

The Reports folder should contain a of running unit tests on the project. Because the project doesn ' t yet have any of the unit tests, which would be uninteresting.

The Libs folder should contain a JAR file is named after the project ' s folder. Further down, you'll be in the can specify the name of the JAR and its version.


8, declaration of dependence-Declare dependencies


The simple Hello World sample is completely self-contained and does not depend on any additional libraries. Most applications, however, depend on external libraries to handle common, and/or complex.

For example, suppose, addition to saying "Hello world!", you want the application to print the current date and Tim E. You could use the "date and time" facilities in the native Java libraries, but your can make things more interesting by us ing the Joda time libraries.

The "a", change Helloworld.java-look like this:

Package Hello;

Import Org.joda.time.LocalTime;

public class HelloWorld {public
  static void Main (string[] args) {
    localtime currenttime = new LocalTime ();
    System.out.println ("The current local time is:" + currenttime);

    Greeter Greeter = new Greeter ();
    System.out.println (Greeter.sayhello ());
  }
Here's HelloWorld uses Joda TIME's localtime class to get and print.

If you ran Gradle builds to builds the project now, the builds would fail because you have don't declared Joda time as a Compil e dependency in the build.

For starters, your need to add a source for 3rd party libraries in Build.gradle.

In ' Build.gradle '
repositories {
    mavenlocal ()
    mavencentral ()
}
The repositories block indicates this build is should resolve its dependencies from the Maven. Gradle leans heavily on many conventions and facilities established by the Maven build tool, including the option of using Maven, as a source of library dependencies.

Now so we ' re ready for the 3rd party libraries, let ' s declare some.

In ' Build.gradle '
dependencies {
    compile "joda-time:joda-time:2.2"
}
With the dependencies blocks, you are declare a single dependency for Joda time. Specifically, you ' re asking for (reading right to left) version 2.2 of the Joda-time library, in the Joda-time group.

Another thing to "about this" dependency is "it is" a compile dependency, indicating that it should be available dur ing compile-time (and if you are were building a war file, included in The/web-inf/libs folder of the war). Other notable types of dependencies include:

Providedcompile. Required dependencies for compiling the project code, but that'll be provided at runtime by a container running the code (for example, the Java Servlet API).

Testcompile. Dependencies used for compiling and running tests, but don't required for building or running the project ' s runtime code.

Finally, let ' s specify the name of our JAR artifact.

In Build.gradle
jar {
    baseName = ' Gs-gradle '
    version =  ' 0.1.0 '
}
The jar block specifies how the jar file would be named. In this case, it would render Gs-gradle-0.1.0.jar.

Now if you run Gradle builds, Gradle should resolve the Joda time dependency from the Maven, the repository and the Buil D would succeed.


9, use Gradle wrapper to build the project-builds your project with Gradle wrapper


The Gradle wrapper is the preferred way of starting a gradle build. It consists of a batch script for Windows and a shell script for OS X and Linux. These scripts allow the You-run a gradle build without requiring that Gradle is installed on your system. To make this possible, add the following blocks to the bottom of your build.gradle.

In Build.gradle
task Wrapper (type:wrapper) {
    gradleversion = ' 1.11 '
}
Run the following command to download and initialize the wrapper scripts:

Gradle Wrapper

After this task completes, you'll notice a few new files. The two scripts are in the folder where the wrapper jar and properties files have been to a added Rapper folder.

└──initial
    └──gradlew
    └──gradlew.bat
    └──gradle
        └──wrapper
            └──gradle-wrapper.jar Gradle-wrapper.properties

The Gradle wrapper is now available for building your project. ADD it to your version control system, and everyone this clones your project can build it just the same. It can be used in the exact same way as a installed version of Gradle. Run the wrapper script to perform the builds task, just like you did previously:

./gradlew Build

The wrapper for a specified version of Gradle, it downloads and caches the Gradle Version. The Gradle wrapper files are designed to is committed to source control so this anyone can build the project without Havin G To install and configure a specific version of Gradle.

At this stage, you'll have built your code. You can be results here:

Build
├──classes
│└──main
│     └──hello
│         ├──greeter.class
│         └──helloworld.clas s
├──dependency-cache
├──libs
│└──gs-gradle-0.1.0.jar
└──tmp
    └──jar └──manifest
        . Mf

Included are the two expected class files for Greeter and HelloWorld, as as a JAR file. Take A quick peek:

For Windows

D:\Java\Spring\Guides\Building Java Projects with Gradle\gs-gradle>jar TVF Build/libs/gs-gradle-0.1.0.jar
0 Wed Sep 10:16:36 CST 2014 meta-inf/
Wed Sep 10:16:36 CST 2014 meta-inf/manifest. Mf
0 Wed Sep 10:04:22 CST 2014 hello/
369 Wed Sep 10:16:36 CST 2014 Hello/greeter.class
987 Wed Sep 10:16:36 CST 2014 Hello/helloworld.class

For Linux

$ jar TVF Build/libs/gs-gradle-0.1.0.jar
  0 Fri May 16:02:32 CDT 2014 meta-inf/-May
 Fri CDT 2014 Meta-inf/manifest. MF
  0 Fri May 16:02:32 CDT 2014 hello/
369 FRI could 16:02:32 CDT 2014 Hello/greeter.class 988 Fri may
30 1 6:02:32 CDT 2014 Hello/helloworld.class

The class files are bundled up. It ' s important to note, which even though you declared Joda-time as a dependency, the library isn ' t included. And the JAR file isn ' t runnable either.

To make this code runnable, we can use Gradle ' s application plugin. Add this to Yourbuild.gradle file.

Apply plugin: ' Application '

mainclassname = ' Hello. HelloWorld '

Then You can run the app!

For Windows

D:\Java\Spring\Guides\Building Java Projects with Gradle\gs-gradle>gradlew run
: Compilejava Up-to-date
:p rocessresources Up-to-date
: Classes Up-to-date
: Run
The current local time is:10:39:09.687
Hello world!

Build successful

Total time:24.859 secs

For Linux

$./gradlew Run
: Compilejava up-to-date
:p rocessresources up-to-date
: Classes up-to-date
: Run
The current local time is:16:16:20.544
Hello world!

Build successful total

time:3.798 secs

To bundle up dependencies requires more thought. For example, if we were building a WAR file, a format commonly associated with packing at 3rd party dependencies, we could Use Gradle ' SWAR plugin. If you are are using Spring Boot and want a runnable JAR file, the Spring-boot-gradle-plugin is quite handy. At this stage, Gradle doesn ' t know enough about your system to make a choice. But for now, the This should is enough to get started using Gradle.

To wrap things up for this guide, which is the completed Build.gradle file:

Build.gradle

Apply plugin: ' java '
apply plugin: ' Eclipse '
Apply plugin: ' Application '

mainclassname = ' Hello. HelloWorld '

//tag::repositories[]
repositories {
    mavenlocal ()
    mavencentral ()
}
//end:: Repositories[]

//tag::jar[]
jar {
    baseName = ' Gs-gradle '
    version =  ' 0.1.0 '
}
// End::jar[]

//tag::d ependencies[]
dependencies {
    compile "joda-time:joda-time:2.2"
}
// End::d ependencies[]

//tag::wrapper[]
task Wrapper (type:wrapper) {
    gradleversion = ' 1.11 '
}
//end::wrapper[]
There are many start/end comments embedded here. This is makes it possible to extract bits of the ' Build ' to ' guide for the detailed explanations. You don ' t need them the your production build file.


10, summary-Summary


Congratulations to you. You have been able to create a simple and efficient Gradle compilation file for compiling Java projects.


Original link: http://spring.io/guides/gs/gradle/

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.