Gradle tutorial for complete beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
have you heard of gradle but you're not really sure what it is why you should use it and how to get started this tutorial will answer all these questions for you and after you've finished watching it you'll be ready to take your first steps with this powerful build tool yes gradle is a build tool also known as a build automation tool i let the cat out of the bag already you'll learn why we need to use build tools in the first place and why gradle in particular is an excellent choice for building java applications gradle gets more usage year by year as developers realize the productivity benefits compared to other options benefits that perhaps you too will want to take advantage of in your own project if you've never used gradle before you're in the right place this is a tutorial for complete beginners after all if you have used gradle but are feeling confused and want to understand the basics this is for you too ideally you should have some knowledge of java as this tutorial is focused on building java applications first up let's get right back to basics to understand why we need build tools anyway since gradle is primarily used for building java applications let's consider a simple java application and what needs to be done to transform it from just being some source code in a repository to being an application ready to be executed here's the code for a simple java application yes it may be the same as the first java application you ever wrote listed on a thousand tutorial websites it's just a single java class in a directory structure this class lives in a file with a java extension also known as the source file it's the code that we as developers write and in theory can read and understand too whether you have a tiny application like this or a huge application it's still just source files in a directory structure maybe there'll be some resources too but how are you going to run this code well you're going to need to compile it first that's right you need to transform the java file to a class file or in other words transform your application from human readable code to machine readable code or in technical lingo bytecode this process of generating the bytecode is called compilation bytecode can be run on the java virtual machine the jvm which is where applications can work their magic and fulfill business requirements or at least print out hello world compiling java code is actually something you can do without a build tool the java development kit the jdk comes with the java compiler command called java z you call java c with a list of all the dot java source files that's not going to be much fun to do by hand it's also very likely that once you get beyond hello world applications you'll need to use functionality provided by third parties or more specifically jar files for example spring boot apache commons lang 3 or guava that's where the compile class path comes in you need to add to it all the jar files referenced by your code in your application in order for compilation to work generating the compile class path is going to be a real pain to do manually especially if you consider the tens or hundreds of libraries that are used by even basic java applications these days i think you get where i'm going with this compiling java code manually gets really tedious really fast this is the main reason build tools exist to make compilation a simple error-free and repeatable process there are many other compelling reasons that build tools exist we don't have time to go into them in depth but here are two important ones testing ensures that your software fulfills its requirements without a build tool you'd have to manually run the tests with the java command and collate the results build tools make life a lot easier packaging your application means putting it into a format that can easily be published and deployed for java applications this is normally a dot jar or dot war file or perhaps a docker image build tools can script this process so that you don't have to remember any long complicated commands hopefully you can see that using a build tool is a much better experience than trying to run commands manually but how can grade will help us here gradle is a build tool designed specifically to meet the requirements of building java applications once it's set up building your application is as simple as running a single command on the command line or within your ide that includes compiling testing and packaging your application all with one command but how does gradle know how to build your application on a high level you have to describe what type of application you're trying to build for example java you need to tell gradle about any libraries your application depends on or in other words its dependencies and any other configuration specific to your application such as special compile or testing options in gradle you provide this configuration in a file called the build script the build script and any other gradle files are committed into your application repository which means anyone that clones your repository can immediately build your application consistently if you're wondering why you should use yet another tool for this process and not create your own script then consider this gradle is designed to perform extremely quickly it has many optimizations that would be very time consuming to create in a custom build script for example once you've compiled your application once when you try to compile again after not having changed anything gradle knows it doesn't need to recompile this feature called incremental build works in many other scenarios and means less waiting around for developers aside from performance gradle has a very advanced dependency management system at a basic level when you define dependencies and run your build gradle downloads them automatically from the internet this makes managing and updating dependencies very simple which you wouldn't get if you were using a custom build script okay so maybe i've convinced you that using gradle is a better idea than creating your own build script but why gradle and why not some other build tool or more specifically the very big elephant in the room maven we don't have time for a full comparison of these two build tool giants but if you are interested in that i do have a video specifically on this topic but in 2004 when maven was first released it was an advanced java build tool for the time gradle came four years later though and was designed to solve son of maven's shortcomings specifically it made defining your build a lot less verbose because it used a code-based build script rather than xml build file since gradle took a code-first approach writing custom plugins and reusing build logic became a lot easier which is very helpful in larger projects finally grader was designed with developer productivity in mind and it performs a lot faster than maven these are all reasons that gradle is now the most popular build tool for open source jvm projects on github anytime you invest learning this tool is well spent as in my opinion it's currently the best option for building java applications and will continue to be for years to come we've covered a lot of theories so far so now if you're interested to see some gradle in action let's jump right in and see how to install gradle and how to create a basic project let's be honest installing software is never glamorous so i'll cut to the chase since gradle runs on java you need java version 8 or above installed as a prerequisite you can verify this by running the java version command which should give you output like this if you don't have java installed you can follow the link in the description to a setup guide now head over to gradle.org install and follow the instructions for installing in windows or using the sdk man or brew package managers i'll very quickly run through the installation process on windows then we can move right onto creating a brand new shiny gradle project download the latest gradle distribution currently 7.2 and unzip it create a gradle directory where you'll be able to add any new versions of gradle and copy the unzipped directory there to be able to use gradle from the command line we need to update the path environment variable to include the gradle bin directory so navigate to the slash bin directory copy the path then press the windows key type environment variables and hit enter click the environment variables button then under system variables double-click path click new and paste in the copied path to the bin directory hit ok ok again and ok again to double check it's all working open up a command prompt type gradle dash dash version and hit enter if you see output that looks like this you're good to move on to the next stage with gradle installed on your machine you can easily create skeletons for new gradle projects on the command line we're going to create the most basic type of project available understand its different components then extend it to build a java application feel free to follow along with the steps in this tutorial yourself which might help you understand the concepts even more thoroughly on the command line create a new directory called gradle dash tutorial wherever you want change directory into it then type gradle space init and hit enter this setup wizard navigates us through the project creation process with three questions the first question is what type of project to generate type 1 for basic project and hit enter next we need to choose which language we want to use for the gradle build script as mentioned earlier the build script is written as code and this can be either groovy or kotlin in this tutorial we'll be using groovy so type 1 and hit enter next we need to choose a project name we'll accept the default of gradle dash tutorial the same as the directory name so just hit enter that's it gradle has created a project for us before we explore it further though let's define what a project actually is it's the highest level construct that represents the application you want to build including the configuration of how to build it so if you've got an application's source code sitting in a repository you'll have a gradle project which also gets committed into the repository with all the information needed to build the application okay so let's take a look at what gradle created when we ran gradle init to keep this concise we'll run through just the most important files used in the rest of this tutorial settings.gradle sets up some high level configuration for the project in our case the project name the file is written in groovy the essentials of which we'll cover shortly it's important to set the project name like this otherwise grader will by default use the directory name which isn't always reliable the next file build.gradle is the build script configuration file describing your application to gradle so it can build it for example here you might say your application is a java application with a particular set of dependencies like settings.gradle build.gradle is also written in groovy right now it's empty with just some comments which means nothing will get built that's fine since we're just exploring the project structure right now and we'll add to this shortly gradle w and gradlew.bat are known as the gradle wrapper scripts gradle w is for linux and mac environments and gradlew.bat is for windows these let you build an application without having to download and install gradle like we did earlier when the wrapper is executed it will automatically download gradle and cache it locally normally you always build your application with the wrapper as it ensures it gets built with the correct version of gradle the only reason we installed gradle separately earlier was so that we could run the gradle init command in an empty directory to initialize this skeleton project for the rest of this tutorial when we interact with our gradle project we'll always use the wrapper the final file i want to draw your attention to is dot git ignore it configures git so that the dot gradle and build directories aren't committed into version control everything else gets committed though the dot gradle directory is a local cache managed by gradle and the build directory is where gradle creates any build outputs such as the compiled java code or jar files you'll see how that works shortly when we get on to building a real java application gradle project doesn't do anything yet its build.gradle is empty and besides there's no code here to compile but we can still interact with it using the gradle wrapper script on windows type gradle w space tasks on linux or mac that's dot slash gradle w space tasks hit enter what we see here are a list of gradle tasks currently available to run in this project okay i got a bit ahead of myself as i haven't yet explained what is a gradal task let's go back to basics then and learn how the four fundamental gradle components of projects build scripts tasks and plugins work harmoniously together to build applications you already know that the project is the highest level grade or concept it's a container for everything that gradle knows about your application each gradle project can have a build script you already encountered this with the build.gradle file created in the gradle tutorial project once again this is where you tell gradle about your application through configuration and gradle uses that information to build it gradle tasks are individual build actions you can run from the command line you might have a task to compile your java code a task to test the code and a task to package the compiled classes into a jar file we saw a list of all the available tasks earlier when we ran the gradle w tasks the way you run a task is by passing its name to the gradle wrapper command for the rest of this tutorial i use the windows version but use whatever is relevant to your environment we used the same syntax earlier when we ran gradle w tasks slightly confusingly tasks itself is a gradle task which you can execute to print out all the tasks this task comes for free with any gradle project as do all the other tasks listed here we won't go through them all but you can always try running any of them yourself to see what they do the last big concept to wrap your head around is the gradle plugin when you apply a plugin in your build script it automatically adds tasks to your project which you can run to achieve some particular outcome for example the java plugin which we'll try out soon automatically adds tasks to compile test and package your application and much more using plugins means you don't have to reinvent the wheel as almost anything you want to do with gradle is covered by either a core or third-party plug-in with this mental model of the four fundamental components projects build scripts tasks and plugins we're almost ready to start adding to the build script but before that if you understand just a few concepts of the groovy programming language the build script will make a lot more sense groovy is a language which like java runs on the java virtual machine the jvm groovy was chosen as a language for gradle build scripts because of its dynamic nature which allows your build to be concisely configured using what's called the gradle groovy dsl dsl stands for domain specific language so writing gradle build scripts involves writing groovy code but doing it in a way that uses the gradle apis since you already know some java you'll be pleased to know that groovy is quite similar let's quickly explore some key differences which gradle makes use of in its build scripts groovy is a scripting language so you can write code outside of a class and execute it it's dynamically typed so you can use the def keyword instead of providing a type semicolons at the end of a line are not required thank goodness brackets are optional when passing parameters to a build if the method has at least one parameter you can define closures using curly brackets closures are blocks of code that get passed around and executed at a later point importantly you don't need to know much groovy to work in grade or build scripts that's because the grade or groovy dsl uses only a subset of the groovy language features so let's move on to writing a simple build script to build a java application and i'll point out the groovy language features as we go first up we need some java code to actually build so i'm going to add a single class by default gradle expects java classes to live in source slash main slash java which is good since you'll always know where to look whatever project you're working in i'll create the expected directory structure then a package of com.tom gregory if you're following along with this tutorial and want to use your own name go ahead i won't be offended under there i'll create a new java source file gradle tutorial.java in there i'll define a gradle tutorial class with the main method which prints out a highly amusing string okay so we've got our class how about we build this bad boy then remember from earlier that we need gradle to take this dot java source file and compile it into a class file in gradle we can do all that with just three lines of code in build.gradle i'm going to delete the comment then we need to apply a plugin which like i said before adds tasks into our project can you guess what the plugin for java projects is called yep it's the java plugin in our build script the way we apply a plugin is to call the plugins method and pass a closure what we're seeing here is just calling a method called plugins with a closure as an argument within the closure we call the id method and pass the string java that's it but what tasks has the java plugin added well to find out let's run the tasks task again yes the task called tasks which prints out all the tasks try saying that while spinning on your head you'll see a load of new tasks but we're just going to focus on the build task which as it says assembles and tests this project let's run the task by passing build to the gradle wrapper notice any difference in our directory structure now we've got a new directory called build that's where gradle creates files during the build process including compiled classes taking a look inside we have a classes slash java main directory which contains the package structure with the compiled gradle tutorial.class file cool so gradle did what we wanted it to in the build libs directory gradle has also created a jar file for us this jar contains the compiled class which in theory we could go ahead and execute let's try that by running java jar build slash libs slash gradle tutorial dot jar okay so we got a big fat error saying no main manifest attribute that just means that java doesn't know which class inside the jar file to run yes i know there's only one class in the jar file to choose from but that's java for you we can easily fix this in gradle by configuring our project to add a main class attribute to the jars manifest file telling java what class to run to understand how you need to know about another task that gets added to our project by the java plugin called jar the jar task is unsurprisingly responsible for creating the jar file and gets executed automatically when we run the build task the way we add the main class manifest attribute is by configuring this jar task to configure it we call a method jar passing a closure then manifest passing enclosure then attributes passing it a map the values of this map are the additional manifest attributes in this case it's a key of main class and a value of the fully qualified class name com.tomgregory.gradle tutorial now gradle knows a bit more about how to generate our jar file so we need to run the build task again to regenerate the jar the new jar should now contain the extra manifest attribute and we should be able to execute it now with the java command that's great it's all working now but before wrapping up this tutorial there are two important aspects to cover that will be essential to working in any gradle java project imagine we want to write a quick test for our application just to make sure it executes without throwing any exceptions in grade all tests go into source slash test java so i'll create this structure then the same package structure com.tom gregory within here i'll create a gradle tutorial test.java source file and inside a test class using the junit 4 library in the test class we have a single test case annotated with app test which checks that the gradle tutorial main method gets executed without throwing an exception if you're not familiar with junit don't worry because what's important is to understand the process of running the test with gradle note that we have an import statement at the top of the file for org.junit.test the junit4 library doesn't come with java so we'll have to add it separately as a dependency for gradle to download and include on the java class path when our test is compiled and run we specify dependencies in our build script by calling the dependencies method passing a closure within that we call the test implementation method passing it a map of the dependencies group name and version any dependency you pass to test implementation will end up on the test compile and runtime class paths this means we'll be able to compile and run the test which has a reference to the junit 4 library remember earlier when i said that gradle automatically pulls dependencies from the internet before it can do that we need to tell it which repository to pull junit 4 from which is the maven central repository we do that in the build script by calling the repositories method passing a closure and then calling the maven central method we have to use brackets in this case to call maven central because in groovy you can only leave out the brackets if the method has one or more parameters let's run the build task again with gradle w build remember from the build tasks description that it assembles and tests the project when gradle executes the task it very briefly shows that it's running the test but so quick you might miss it fortunately we can consult a test report generated in build slash reports slash tests slash test open the index.html file in a browser and we see that one test was executed with zero failures awesome you've just seen how to apply the java plugin to gradle project letting you compile java code with the build task the build task also generated a jar file which we had to configure to include a manifest attribute in order to execute it finally we configured the repositories and dependencies to include junit 4 for tests and got gradle to successfully execute our test case here's the final build script for the gradle tutorial project which you can also download by following the repository link in the description if you were a complete gradle beginner when you started watching this tutorial then congratulations on taking your first steps with this build tool if you want to continue learning gradle then i invite you to take my free course get going with gradle whilst what you learnt in this tutorial was indispensable as a first introduction the get going with gradle course is the fastest way to a working knowledge of gradle where you'll feel confident working with simple gradle projects thanks for watching i hope to see you again soon in another video
Info
Channel: Tom Gregory Tech
Views: 4,603
Rating: undefined out of 5
Keywords:
Id: -dtcEMLNmn0
Channel Id: undefined
Length: 24min 47sec (1487 seconds)
Published: Wed Oct 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.