[Gradle] Building Systems with Gradle under Eclipse

Source: Internet
Author: User



Reprinted from: http://www.ibm.com/developerworks/cn/opensource/os-cn-gradle/



When building systems, it is often necessary to use Ant, Maven and other tools, and for beginners, they are too complex to get started or take time. This article will introduce to the reader a new way of building the project Gradle, it is simple, quick to use, can greatly save the project time and cost.


Build your system with Gradle under Eclipse


Basic development environment


    • Operating System: This tutorial uses Windows Vista Enterprise, if your system is Linux, choose to download the corresponding version of the other tools, including development tools, Java EE server, Apache Ant, SoapUI.
    • Development tools: Eclipse IDE for SOA developers version, please go to the http://www.eclipse.org/downloads/website to download, of course, any version of Eclipse is possible.
    • Java EE Server: apache-tomcat-6.0.18, can be downloaded to http://tomcat.apache.org/download-60.cgi, using any version of more than 5.0 can be, of course, you can also use other Java EE server such as Jboss.
    • Jdk: Download the 1.5.0_17 version to http://java.sun.com and install it after downloading.
Ant,maven,gradle Simple Comparison


Ant is what we used to build the system, the XML script file includes a number of task tasks, the tasks can be interdependent, for a large project, these XML files are not easy to maintain, and those who are dependent on the project and no version number of the Jar package, Sometimes it really hurts, and then Maven comes up, and the central repository-based compilation is really a lot better than Ant, but isn't ant,maven the only choice we have to build a project? Oh, of course not, using Gradle to build the system I think that will be the best choice for Java construction projects, simple, fast, no harsh requirements for beginners, can be said to be used, and we no longer have to look at those lengthy and complex XML files, because Gradle is based on Groovy Language, Groovy everyone should be familiar with it, is based on Java Virtual Machine's Agile development language, which combines many powerful features of Python, Ruby and Smalltalk, and if you are a full supporter of Ant, there is no problem because Grad Le can be very smooth to call Ant file, I say you may not accept Gradle, below we will be a specific example to explain the process of ant,maven,gradle construction projects, through examples we can easily understand their differences. Let ' s go.


Using ANT to build a simple system


Create a new Java project named Ant_project


Figure 1. New Ant_project Project


And then create a new HelloWorld class, and here's what we're going to do with Ant to compile, package, and list the code for the class as shown in Listing 1:


Listing 1. HelloWorld class
package org.ant.test; 

 public class HelloWorld { 
     public String sayHello(String name){ 
         return "Hello "+name; 
     } 
 }





Then create a new build file named Build.xml, as shown in Listing 3:


Listing 2. Build.xml
 <?xml version="1.0" encoding="UTF-8"?> 
 <project name="project" default="default"> 
    <target name="default" depends="depends" description="description"> 
        <javac srcdir="src" destdir="bin" includes="org/**"></javac> 
         <jar basedir="bin" destfile="dist/ant_project.jar"></jar> 
         <war destfile="dist/ant_project.war" webxml="WEB-INF/web.xml"> 
             <classes dir="bin"></classes> 
         </war> 
    </target> 
    <!-- - - - - - - - - - - - - - - - - - 
          target: depends                      
         - - - - - - - - - - - - - - - - - --> 
    <target name="depends"> 
    </target> 
 </project>





The students who are familiar with ant should be able to see the above script very easily, and it is not explained in detail here, the main function is to compile the project and then make the jar and the war package. The directory structure of Ant_project so far is shown in 2:


Figure 2. Ant_project Project directory Structure


Run the ant script.


E:\gdcc\tools\apache-ant-1.6.5\bin\ant-f  
Note: Ant is placed under the E:\gdcc\tools\apache-ant-1.6.5 directory. The results of the implementation are as follows:
 Buildfile: E:\ws_IBM\ant_project\build.xml 
 depends: 
 default: 
    [javac] Compiling 1 source file to E:\ws_IBM\ant_project\bin 
      [jar] Building jar: E:\ws_IBM\ant_project\dist\ant_project.jar 
      [war] Building war: E:\ws_IBM\ant_project\dist\ant_project.war 
 BUILD SUCCESSFUL 
 Total time: 859 milliseconds





This is a very simple project, we put him into a Jar,war package, the required build file about 10 rows or so, let's look at the situation with Gradle.


Use Gradle to build a simple system readiness environment:
    1. Download Gradle-0.9-preview-1 Select a version from the Http://dist.codehaus.org/gradle/?ref=darwinports.com website and extract it to the specified directory, and the Gradle bin The directory is added to the Path variable.
    2. Using the cmd command, and then typing gradle–version, the following information appears, indicating that the environment was configured successfully.
 C:\Documents and Settings\suchu>gradle -version 
 Gradle 0.9-preview-1 
 Gradle buildtime: Monday, March 29, 2010 4:51:14 PM CEST 
 Groovy: 1.7.1 
 Ant: Apache Ant version 1.8.0 compiled on February 1 2010 
 Ivy: 2.1.0 
 Java: 1.6.0_12 
 JVM: 11.2-b01 
 JVM Vendor: Sun Microsystems Inc.





Note: The above information may differ according to different versions of Gradle or different environments, but they are all correct.


Introduction to the commonly used methods of Gradle


Create a new Java project named Gradle_project


Figure 3. New Gradle_project Project


Then create a new Java bean named HelloWorld content and the same as above, you can refer to Ant_project. In order to compile and package the function, we need to create a new file named Build.gradle. The file contents are shown in Listing 3:


Listing 3. Build.gradle Content
Apply plugin: ' java '





is not very surprised, indeed, really as long as so short line, and its function is quite powerful, can compile, hit into jar package, run test script and so on. So far, the structure of the project is shown in 4:


Figure 4. Gradle_project Project Structure diagram


One thing to note here is that the structure of a project package is best built according to Gradle expectations, but can also be changed by configuration. Let's run the next Build.gradle file. Run the cmd command, enter the Gradle_project project path, and then run the Gradle Build command, and the command displays the information as shown in Listing 5.


Listing 5. Build.gradle Running Display information
 E:\ws_IBM\gradle_project>gradle build 
 :compileJava 
 :processResources 
 :classes 
 :jar 
 :assemble 
 :compileTestJava 
 :processTestResources 
 :testClasses 
 :test 
 :check 
 :build 

 BUILD SUCCESSFUL 

 Total time: 5.125 secs





Let's look at the generated object, this command first creates a new build directory under Gradle_project, the build directory contains classes, Dependency-cache, libs,tmp four directories, Libs contains the jar package, and the jar package contains M All Java files and resource files under Ain. A simple example to show here, how is not the script is very concise, easy to use, produce want to continue to study interest, don't worry, below we will continue to explore the magic of Gradle.



Here we introduce a few common commands, clean, this command is to delete the build directory just generated, Assemble, this command is to compile the Java file but do not run to check the quality of the code, such as the command, the runtime displays the information shown in Listing 6:


Listing 6. Information displayed by the assemble command
E:\ws_IBM\gradle_project>gradle assemble 
 :compileJava 
 :processResources UP-TO-DATE 
 :classes 
 :jar 
 :assemble 

 BUILD SUCCESSFUL





Compared to listing 5, their differences should be easy to see, so how do we run a command that checks the quality of the code without needing to do extra work like a jar package, which is exactly what you want, the command is to compile the Java file and run those similar CHECKSTYLE,PMD and other external plug-in commands to check our own source code. The Check command runs the displayed information as shown in Listing 7:


Listing 7. Check command run-time information
 E:\ws_IBM\gradle_project>gradle check 
 :compileJava UP-TO-DATE 
 :processResources UP-TO-DATE 
 :classes UP-TO-DATE 
 :compileTestJava UP-TO-DATE 
 :processTestResources UP-TO-DATE 
 :testClasses UP-TO-DATE 
 :test UP-TO-DATE 
 :check UP-TO-DATE 

 BUILD SUCCESSFUL





One thing to note here is that Gradle is compiled incrementally and compiles only those Java classes or resource files that have changed, such as up-to-date, which is updated. Now Javadoc more and more attention, especially for those complex need interface calls of the project, Javadoc position is more prominent, if we use Ant need to add the fragment of listing 8 in the build file.


Listing 8. Using ANT to generate Javadoc
<target name = "javadoc">
        <!-destdir is the directory location generated by javadoc->
       <javadoc destdir = "$ {distDir}" encoding = "UTF-8" docencoding = "UTF-8">
           <!-dir is the location of your source code, remember the location of the java file, not the class file,
                        This command is easy to ignore for the first time. Remember->
                 <packageset dir = "$ {srcDir}">
            <!-exclude is to remove those class files that do not want to generate javadoc->
                              <exclude name = "$ {excludeClasses}" />
                                    </ packageset>
                            </ javadoc>
         </ target>





Then we run with the ant Javadoc command to generate the Javadoc. So how do we use Gradle to generate Javadoc, and do we need to do the extra work? Does the build.gradle file need to be modified? Our answer is, no, nothing to change, nothing to do, just use the Gradle javadoc command, you can generate the Javadoc we expect. Usually we create a new project, and the contents of the. classpath file are shown in Listing 9:


Listing 9. . classpath File Contents
<?xml version="1.0" encoding="UTF-8"?> 
 <classpath> 
     <classpathentry kind="src" path="src"/> 
     <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER
        /org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/jdk1.6.0_12"/> 
     <classpathentry kind="output" path="bin"/> 
 </classpath>





Through the above knowledge, we know that Gradle expected directory structure and automatically generated by some differences, such as the source path, compiled file placement directory, etc., then we can be unified by Gradle command, so that the original project structure and Gradle expectations of the same, In case the developer puts the code in the wrong directory structure, the Gradle does not manage them. Here we have a simple way to achieve the above requirements, first we have to simply modify the next Build.gradle file, add apply plugin: ' Eclipse ' this line, and then we use the command Gradle Eclipse can: Classpath The file changes as shown in Listing 9.


Listing 9. Modified. classpath File Contents
 <?xml version="1.0" encoding="UTF-8"?> 
 <classpath> 
  <classpathentry kind="src" path="src/main/java"/> 
  <classpathentry kind="output" path="build/classes/main"/> 
  <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> 
 </classpath>





The war pack is something we often use, and we used the Ant script to generate the war package, so how does Gradle generate the war package? After the above study perhaps you have guessed out, need to add a plugin, completely correct, just want to apply plugin: ' War ' this line to add to Build.gradle file, and then run Gradle War command can, simple is absolutely deadly, is not, hehe!


How to use Gradle on an old project


As we have said above, Gradle has certain requirements for the directory structure that it can control, so if our project has been started for a long time, the current project structure does not meet the requirements of Gradle, then can we still use Gradle? The answer is, of course, yes, we'll show you how to use Gradle on an old project, which is simple, but if it's too complicated, we don't need to introduce it here, just use Ant. First we need to add the content shown in Listing 10 to the Build.gradle file.


Listing 10. Match the structure of the old project
sourceSets { 
     main { 
         java.srcDir "$projectDir/src"
     } 
 }





Then we can use all the commands and methods provided by Gradle.


How to add a jar package that the project relies on


As you all know, a project relies on many jar packages during the compilation process, and in Ant we do this by adding classpath, as shown in Listing 11.


Listing 11. Adding dependent jar packages to ant
 <path id="j2ee"> 
         <pathelement location="${servlet.jar}" /> 
         <pathelement location="${jsp-api.jar}" /> 
         <pathelement location="${ejb.jar}" /> 
         <pathelement location="${jms.jar}" /> 
 </path> 
 <javac destdir="${build.classes}" srcdir="${src.dir}" debug="${javac.debug}" 
                 deprecation="${javac.deprecation}"> 
             <include name=" "/> 
             <classpath refid="j2ee"/> 
 </javac>





So how did Gradle do it? Through the above knowledge of learning, do you have a general idea? If we now have a Java class called HelloWorldTest, which references the classes in JUnit's jar package, how do we use Gradle to compile this class? First we create a new directory called Libs, this directory is to place the project depends on all the jar package, of course, including the HelloWorldTest class depends on the Junit-4.4.jar package, and then we want to modify the Build.gradle file, add the content shown in Listing 12.


Listing 12. How the project relies on jar package additions
repositories { 
     flatDir(dirs: "$projectDir/libs") 
 } 
 dependencies { 
     compile ‘:junit:4.4‘
 }





Note: Repositories is quite a repository for storing jar packages, we can specify local dependent jar packages, or use the warehouses specified by Maven, such as mavencentral (), and dependencies to include all the jar packages that are really dependent, the format For Goup:name:version, ': junit:4.4: ' Is the Junit-4.4.jar of this package that represents the dirs path.


How to implement copy work


Copy is a command that we often use, a copy of the Java class, a copy of the resource file, and so on. If it is Ant we will add the content in Listing 13 to the Build.xml file.


Listing 13. Copy task in Ant
Copy a single file to another file
   <copy file = "myfile.txt" tofile = "mycopy.txt" />
Copy a single file to a directory
   <copy file = "myfile.txt" todir = "../ some / other / dir" />
Copy a directory to another directory
   <copy todir = "../ new / dir">
     <fileset dir = "src_dir" />
   </ copy>
Copy part of a file to a directory
   <copy todir = "../ dest / dir">
     <fileset dir = "src_dir">
       <exclude name = "** / *. java" />
     </ fileset>
   </ copy>
   <copy todir = "../ dest / dir">
     <fileset dir = "src_dir" excludes = "** / *. java" />
   </ copy>





We know that there are many properties in the copy task, and we don't list them here, but we'll look at how Gradle is going to implement them.


Using Gradle to implement copy file tasks between directories


We only need to include the contents of listing 14 in the Build.gradle file.


Listing 14. Implementing inter-directory copy files in Gradle
 task copyOne(type: Copy) { 
     from ‘src/main/test‘
     into ‘build/anotherDirectory‘
 }




Note: Copy all files under the test directory to the Anotherdirectory directory. We then use the command E:\ws_ibm\gradle_project>gradle Copyone to execute. filtering on Copy files


Sometimes the number of files in a directory is very large, and we just want to copy a certain part of the file, such as copying only Java files or resource files, we need to use the copy task's include property, which is the same as Ant. For example, to copy only Java files to a specified directory, to achieve this requirement we want to add the contents of listing 15 to the Build.gradle file.


Listing 15. Copy the Java file to the specified directory
task copyTwo(type: Copy) { 
     from ‘src/main/test‘
     into ‘build/anotherDirectory‘
     include ‘**/*.java‘
 }





If we just want to exclude some files and do not want to copy this type of file, we need to use the Exclude property, for example, we do not want to copy the Java file to the specified directory, then we just need to replace the include in listing 15 above with exclude.


Publish the Jar file


When you do a project, you often encounter a class in project that relies on another class in project, and if you use ANT, we will do this by first making the dependent class file into a jar, and then using the Copy command to copy the jar package to the specified directory, and we can imagine going to the build . xml add a lot of lines of code, here we do not list, not the students can refer to the above knowledge. Below we look at how Gradle to complete this demand, Gradle not only can tell the JAR package is published to the local directory, but also can be published to the remote directory, we look at the contents of listing 16.


Listing 16. Publish the jar package to a local directory
publishJarFile { 
     repositories { 
         flatDir(dirs: file(‘jarsDerectory‘)) 
     } 
 }





Then we can use the Gradle publishjarfile command. Note: Listing 16 is all the Java class files under the project into a jar package, which is then placed in the Jarsderectory subdirectory under the project directory.



MAVEN's warehouse management approach to the jar package provides us with a lot of convenience, and Gradle can take advantage of Maven's advantage, and we've already talked about how to use it, so how do we update the jar packages needed by the project to the warehouse? The specific solution is shown in Listing 17.


Listing 17. Publish the jar file to Maven's repository
apply plugin: ‘maven‘
 publishToMaven { 
 repositories.mavenDeployer { 
 repository(url: "file://localhost/tmp/myRepo/") 
 } 
 }




Application of Gradle in multiple projects


When doing projects, often encounter a number of projects, the most common situation we are divided into the server side and the client two parts, this situation we used to Ant time in each project to build a Build.xml file or create a build.xml file, and then in this Build.xml the target of different projects in the file, and will be referenced to the project into a jar package for other projects to reference, then Gradle how to complete such a demand? Let's give a concrete example to illustrate this in detail. First we create a new main project named Gradle_multiproject, and then under the main project in a new sub-project named Sub_projectone, under the two projects have a separate SRC and meet the gradle requirements of the directory structure, Under each project, a class named HelloWorld is built, and the class content is the same as listing 1. Then we create a new Settings.gradle file, as shown in Listing 18.


Listing 18. Settings.gradle File Contents
Include "Sub_projectone"





Then create a new Build.gradle file that we are familiar with, with the file contents shown in Listing 19.


Listing 19. Build.gradle file contents under Main project directory
 Closure printProjectName = { task -> println "I‘m $task.project.name" } 
 task hello << printProjectName 
 project(‘:sub_projectone‘) { 
     task hello << printProjectName 
 }





We then use the command gradle–q hello to run the result as shown in Listing 20.


Listing 20. Command Run result
 E:\ws_IBM\gradle_multiProject>gradle -q hello 
 I‘m gradle_multiProject 
 I‘m sub_projectone





We will find that this command prints out the names of both the main project and the sub-project. I think you must have guessed right, because we used the project () method in the Build.gradle file, the name of the sub-project is passed in the method, if we have more than one sub-project, then how can we call it? At this point we only need to call another method allprojects, note that the Allprojects method does not need to pass in parameters, it returns a list of all the sub-projects under the current project and the current project. The above demonstration of the content we do not often use, here is a simple introduction to illustrate that Gradle provides us with a lot of ways to call us, in the multi-engineering environment we can use them flexibly to meet our requirements, we will step into the subject to see in the multi-engineering situation, Gradle How to compile and package the respective projects. Here we add some content to the Build.gradle file, as shown in Listing 21.


Listing 21. Content added to the Build.gradle file
 subprojects{ 
 apply plugin: ‘java‘
 }





Then we use the command Gradle build, found that all the sub-projects under the main project have a new build folder, which contains the compiled generated class files and jar files, and the main project SRC code is not compiled, packaged. So what can we do to get both the main project and the sub-project to be compiled and packaged? The method is simple, we only need to add the Build.gradle file to the application plugin: ' Java ' such a line of code, now the full build.gradle content is shown in Listing 22.


Listing 22. Full Build.gradle file content
 apply plugin: ‘java‘
 subprojects{ 
 apply plugin: ‘java‘
 }





It's hard to imagine that just a few lines of code are done to compile all the code in the project and make the jar file. Some friends will ask, if the sub-project and the main project they hit the package is not the same, some need jar package, some need to fight a war package and so on, such a demand we how to do it, very simple we only need to fight in the war package to create a new Build.gradle file, the file content for Apply plugin: ' War ', and then we use the Gradle Build command in the main project directory to generate the war package we need, and Gradle is using this method to satisfy that differentiated requirement.



Friends who use Ant will have a deep feeling! Maybe some friends will have some negative voices, especially for those ant enthusiasts, will say, ant if you use the good, the package is good can be very concise and can achieve this effect, it is true, Gradle is just a few of the features we often use to encapsulate the method, Then we call these methods, and again, Gradle call ant script is OK, if you must use ant, then you use Gradle to organize logic is also a good choice. Let's briefly look at how the Gradle Chinese call the Ant script.


Call Ant script in Gradle


First we build Ant file Build.xml, the file details are shown in Listing 23.


Listing 23. Build.xml File Contents
 <project> 
    <target name="hello"> 
        <echo>Hello, from Ant</echo> 
    </target> 
 </project>





Then we are building a Build.gradle file, the file details are shown in Listing 24.


Listing 24. Build.gradle File Contents
Ant.importbuild ' Build.xml '





Simple, a word of things just, hehe. We then use the Gradle Hello command to look at the results, as shown in Listing 25.


Listing 25. Gradle running results of calling ANT files
E:\gdcc\me\gradle-0.9-preview-1\samples\userguide\ant\hello>gradle hello 
 :hello 
 [ant:echo] Hello, from Ant 

 BUILD SUCCESSFUL 

 Total time: 9.734 secs





As you can see, it is true that the Ant build.xml file is being called.


Summarize


This tutorial is a concrete example of how to use Gradle to build engineering, and in specific instances to introduce our familiar ant to compare the completion, so that the ant enthusiasts can get started faster, and can see the pros and cons of both, and finally explain how and Ant to integrate, Each example is through the beginning of the new project to continue to lead the people, we know that only through a piece of paper to very detailed Gradle all aspects of the very clear, it is impossible, this tutorial provides the most basic, the most basic development process, any complex transactions in the final analysis or from the foundation , I have always advocated, "give the fish, rather than grant to the fishing", I think as long as the direction of the right, know how to do, there will be no big mistake. Finally, I wish everyone a smooth work.


Reference Learning
    • Http://www.ibm.com/developerworks/cn/java/j-pg12144.html introduces the combined application of Grovy and Ant.
    • http://www.ibm.com/developerworks/cn/linux/sdk/ant/a simple introduction to Ant's Basic usage.
Access to products and technologies
    • Eclipse ide:http://www.eclipse.org/downloads/.
    • ant:http://ant.apache.org/.
    • Gradle:http://dist.codehaus.org/gradle/?ref=darwinports.com.
    • tomcat:http://tomcat.apache.org/download-60.cgi.


[Gradle] Building Systems with Gradle under Eclipse


Related Article

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.