Gradle Course for Beginners | Get Going with Gradle

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome to get going with Gradle the fastest way to a working knowledge of Gradle before we get started here's a quick overview of what to expect from this course and how to make the most of it so one thing you might be wondering is who is this course for well it's specifically for anyone that finds themselves in one of these scenarios maybe you have no greater knowledge and you want to get started fast this course will help you get there or you might have used Gradle for a while but aren't confident making changes to a build or perhaps you know some Gradle but want to better understand the fundamentals before learning about more advanced topics if any of these sound like you then you're in the right place what can you expect to learn from this course well by the end of the course you'll understand when to use Gradle you'll have created your first Gradle project you'll be able to create a simple Java project in gradual you'll understand the key aspects of a Gradle build file and you'll know how to write code using groovy the Gradle scripting language ultimately by the end of the course you'll be more confident and effective working with Gradle with a solid foundation on which you can build on in the future this is a standalone course which means as long as you put in the effort you'll achieve the previously stated learning outcomes without any additional resources that said if you already know you want to go beyond simple projects and achieve full Mastery of building Java applications with Gradle then Gradle hero is likely the course for you you fall into this category then I'll give you a few more details at the end of this course finally here's some information about how you can make the most out of this course the first thing to note is that all this course is delivered through video lessons some lessons are theoretical or you just need to understand the concepts others are practical where you'll get the most benefit by actually doing the steps that you see me do in the video yourself I tried to make myself as understandable as possible but if you need to you can slow down the video or even speed it up specifically for the Practical lessons I've included full step-by-step written instructions below the video of what you need to do at this point that's everything you need to know before starting this course so now it's time to get going with Gradle welcome to this first lesson where you'll get a high level overview of Gradle including what it is why you would use it why it's so powerful and what makes it better than other build tools let's get right into it so first up let's answer the question what is Gradle primarily it's a build automation tool and the build automation tool takes all the code in your project and packages it up into a Deployable unit that can be run in the Target environment bradle can be used to build small projects quickly or build very complex projects that take a long time Gradle builds are written in groovy which is the scripting language built on top of the Java virtual machine the jvm you can also write Gradle scripts using another Java jvm language called kotlin in this tutorial though we'll be focusing on the most popular groovy version in later lessons we'll be looking a bit deeper into a few important characteristics of groovy to enable you to properly understand Gradle build Scripts it's highly configurable meaning that even if you have some obscure requirement in your build you'll almost certainly be able to find a way to do it in Gradle so why would you use Gradle well Gradle makes building and running applications very easy because it's specifically designed for this purpose it's very likely that if you try to create a build mechanism yourself or your application from scratch you'll waste a lot of time and end up with something not as performant and streamlined as you would with Gradle there's no need for people using your projects to install Gradle because the wrapper script which we'll talk about in a later lesson comes bundled with Gradle projects just download the git repository and run dot slash Gradle w space build to build the project it's that simple Gradle is very concise and less verbose than tools like Maven because the build is defined in code and not XML lastly it's very performant and supports incremental builds so you don't have to do the same things multiple times unnecessarily for example it won't rerun the same tests again if the code hasn't changed what are the key Gradle Concepts we'll be covering each of these in more detail later on but here's a quick overview of the most important components of Gradle build.gradle is your Gradle build script file where you'll Define how your project is built is written in groovy and uses a Gradle domain specific language or DSL to make defining your builds as concise as possible all this means is that it uses some special groovy language features we'll cover later on to keep things neat and tidy if you've used Maven before the build.gradle is equivalent to maven's pom.xml file finally before we get into an example the build.gradle lives at the top level of your project I think it's time now to jump into a simple example of what a Gradle build file looks like don't worry about understanding every detail here for now because we'll be covering this again later on plugins are the main way you can add more functionality to your build here you can see we've got the Java plugin which adds capabilities like compiling Java code and running tests we'll cover exactly how this works in a later lesson metadata such as your projects group and version are important to specify they may get used in different places in your build like in the naming of artifacts such as Java jar files if you're wondering where the name of the project is specified that's in a different file settings.gradle which we'll explore in a later lesson repositories is where your build's dependencies are downloaded from a very common repository for Java projects is Maven Central but Gradle also supports J Center Google and you can even specify your own private Repository lastly dependencies are artifacts that are required in order to build your project during your build Gradle downloads these dependencies from the repositories we just spoke about some common examples include junit for running tests which you can see here or spring boot for building a web application the next key concept I want to introduce is the Gradle task a task defines a unit of work to be executed in your build this could be anything from compiling your code to deploying it to a remote Repository you can invoke one or many tasks from the command line and here's an example of running the build task which compiles and tests a project if you're wondering what the dot slash grade or w means that's just how you invoke Gradle and we'll talk about it in a minute you can see a list of available tasks in your project by running dot slash Gradle w space tasks of course like most things in Gradle you can create your own custom tasks if the functionality you need doesn't already exist tasks can have dependencies on other tasks this means that the task which is depended on gets run first all the dependencies between tasks in a project create what is called the Gradle task graph and here's how some of the task graph looks for the build task the build task depends on the assemble task which packages the application and it also depends on the check task which runs tests the last key concept I want to cover in this introductory lesson is the Gradle wrapper now this is a script which you can use to invoke Gradle and run tasks on the previous slide we talked about the build task you can run the build task in Mac or Linux environments by running dot slash grade or w space build in Windows environments it's Gradle w dot bat space build importantly the wrapper script is always committed into your Project's Version Control System this means for someone who wants to build your project there's no need for them to have Gradle installed on their machine they can just check out your project and build it the Gradle wrapper also contains a specific version of Gradle this avoids any incompatibility problems since you know that your Project's build works with a specified Gradle version for these reasons you should always use the Gradle wrapper script by running dot slash Gradle W or grade or w dot bat the only time that you wouldn't use the Gradle wrapper script is when you need to initialize a new Gradle project which you can do using a local Gradle installation we'll cover that in a practical lesson later on before we complete this lesson here are the key points to take away Gradle is a modern flexible customizable build automation tool and Gradle build scripts written in The Groovy programming language the build script is contained in the build.gradle file and it contains plugins metadata repositories and dependencies all of which we'll cover again in later lessons tasks in Gradle represent a unit of worked and are linked together through the Gradle task graph you run tasks using the Gradle wrapper script checked into your Project's Version Control System so that's everything I wanted to cover here I look forward to joining me in the next lesson welcome back and in this lesson we're going to run through how to install Gradle on your machine and how to validate the installation now whether you're a Windows Linux or Mac User I'll cover the steps you need to take first off though as a prerequisite because Gradle runs in Java you're going to need the Java jdk to be installed I favor Java version 11 which is the current long-term support version I won't be running through the steps of how to install Java as it's outside the scope of this course but I'll provide a download link in the notes below this lesson so here are the steps we're going to take to install Gradle first off we'll validate that Java is installed properly secondly we'll download Gradle and set it up in our environment next we'll validate the Gradle has been installed and I'll run through installation separately for Windows then Linux environments and if you're on a Mac you can use the Brew package manager to install Gradle which I'll cover at the end of this lesson and feel free to follow along with the steps as I do them or watch the full video and complete the steps afterwards and with all my practical lessons you'll find full step-by-step instructions in the notes below this video I'm going to start by demonstrating how to install Gradle in Windows first off we need to open the windows command prompt to do that open the start menu type CMD then hit enter now we're going to validate that Java is installed type Java Dash version and it should print out the details of your current Java installation if it looks like this you're good to continue don't worry if you've got a different Java version installed because Gradle supports versions 8 and above next we're going to download the Gradle binary open a browser and go to gradle.org releases scroll down and choose the most recent Gradle release at the time of recording this was 6.8 but if you see a more recent version you can download that instead let's choose the binary only option click the link to download the grade or zip file to your computer while that's downloading we're going to create a Gradle directory on the hard drive and extract the zip file into that directory first let's open the file explorer to do that open the start menu type file then hit enter navigate to your hard drive root directory in my case that's the C directory right click new folder and type Gradle Now navigate to where you've downloaded the Gradle zip file copy the zip file and paste it in the new directory you just created now you can right click the zip file and select extract tool to extract the zip file using Windows I'm actually going to use a program called 7zip which seems to be much faster than Windows and I'll provide a link in the notes you should now have an additional directory go into that directory go into the bin directory and I want you to copy the path from the address bar at the top of the file explorer so click on that and copy in and save that for later on because we'll need it now we need to configure your path variable so that you can run Gradle commands from wherever you are in the command prompt go to the start menu type environment then hit enter when the edit the system environment variables appears on the dialog that opens click environment variables that under system environment variables double click on the path variable we're going to add a new entry into this path variable for our Gradle installation click new and paste in the location of the Gradle bin directory which you copied earlier hit enter select ok again and okay again now let's close these windows and close the command prompt and we're going to open a new command prompt so go to the start menu type CMD enter and now we're going to validate our Gradle installation type Gradle dash dash version hit enter and at this point you should see some output like this showing us that the specific version of Gradle is installed properly if you're a Windows user well done that's all you need to do before moving on to the next lesson if you want to see the setup steps for Linux environments then stay on for the rest of this video now let's cover the Gradle installation on Linux and I'm going to be setting this up in Ubuntu Linux but the steps should be very similar for other versions I'm going to be running all these commands from the Linux command line remember you can find all the commands and step-by-step instructions in the notes below this video first we're going to validate that Java is installed using Java Dash version paste in the command hit enter and it should print out the details of your current Java installation if it looks like this you're good to continue don't worry if you've got a different Java version installed because Gradle supports versions 8 and above now let's download the latest version of Gradle which I'll do using the curl command paste it in from the instructions and hit enter to download the Gradle zip file to your home directory now that's downloaded we'll unzip the file using the unzip command so paste it in hit enter and if you're prompted for your password enter it because we're running the command as the root user now we can look at the contents of the Gradle installation using LS paste in the command and hit enter and you should see some files and directories like this now let's set up The Path environment variable to include the path to Gradle this will mean we'll be able to run the Gradle command from wherever directory we happen to be in to do this we'll make a change to your user's dot bash RC file in your home directory dot bash RC contains configuration which gets loaded every time you start a terminal session paste in the Echo command and hit enter now I'm going to close this terminal session and open up a new one to prove everything's set up correctly let's use the Gradle dash dash version command to show that Gradle has been successfully installed paste it in hit enter and if you see output like this you're good to go finally before we finish this lesson here are a few more installation options if you're using a Mac you can use the Brew package manager to install Gradle just run Brew install Gradle if you're using the sdkman package manager the command is SDK install Gradle then the Gradle version whatever your environment you should now have greatly installed if you have any problems at all feel free to send me a message that's everything I wanted to cover in this lesson I look forward to joining me in the next lesson welcome back and in this short lesson you're going to learn about the basic structure of a Gradle project in preparation for building your first Gradle project in a later lesson before we get into the structure of a simple project note that Gradle does support both single projects and multi-project build structures if you've used Maven before you might be familiar with these Concepts a single project structure is normally what you'd use when you have a small project to build which produces a single build output on the other hand a multi-project structure is used for a complex project which is split into several distinct components Each of which may produce their own build outputs in this introductory Gradle course we'll be going into detail on the single project structure which is more than sufficient for many real-world use cases what you can see here is the file structure of a simple single project Gradle build in fact this project is so simple that the only files here are related to Gradle itself this allows us to really understand what is related specifically to Gradle before we start adding code to our project in later lessons the first file is build.gradle which you should already be somewhat familiar with from a previous lesson it's the main file where we Define how our Gradle build should work including adding plugins metadata repositories and dependencies we'll be covering it again in more detail in later lessons next is the Gradle directory which contains the code and configuration of the Gradle wrapper then we've got the wrapper scripts themselves as I described earlier is the Gradle W script for Linux and Mac environments and Gradle w dot bat for Windows environments since both of these files are committed into Version Control your project can automatically be built in all of these environments without needing to install Gradle separately lastly is the settings.gradle file this contains additional configuration for your project outside of the build.gradle importantly here you can specify the project name which gets used in various places such as for naming generated build artifacts importantly all of the files and directories from the previous slide should be committed into Version Control there is one additional hidden directory the dot Gradle directory which should not be committed into Version Control this is a Project Specific cache used internally by Gradle we don't need to know any more details other than that it should be added to our git ignore file and not committed to Version Control fortunately when you use Gradle to generate your project it automatically generates the corrects.get ignore file but I think it's important to know what is and isn't stored in Version Control which hopefully you've understood from this lesson that's everything I wanted to cover about Gradle project structure the next lesson is a practical where we're going to use the Gradle installation from earlier to generate our first Gradle project I look forward to joining me in the next lesson welcome back and I'm really excited you're joining me for this lesson where we're finally going to create a Gradle project let's get right into it this is another practical lesson where you can follow along with this video or watch the video then complete the steps afterwards so what will we be doing first we're going to use the Gradle installation we set up earlier to run the Gradle init command which bootstraps a brand new Gradle project the time to use Gradle in it is when you've got a new empty project or a project which doesn't run in Gradle yet and you want to generate all the necessary Gradle build files quickly and easily the Gradle init command comes with a setup wizard which we'll run through to understand the different options then once the project has been generated we'll step through each of the new files and directories finally just like with a real project we'll commit it into Version Control using git on a practical note I'm going to be using a Linux environment for this demonstration the steps for Windows will be almost the same but I'll make sure to show both versions as a pop-up on screen and in the notes below this video open up a terminal and navigate to your home directory or wherever you want to create this new Gradle project let's create a directory for the project called get going with Gradle type or copy from the instructions mkdir space get going with gradual then hit enter navigate into the directory by typing CD space get going with Gradle then hit enter at this point we're in a new empty directory so we can create our first Gradle project type the command Gradle space init then hit enter this initializes the Gradle Setup Wizard which will ask us several questions about the project we want to create first question is what type of project we want to create basic application library or a Gradle plugin we're going to create a basic project to type one then hit enter next we can choose whether to write our build script in The Groovy or kotlin language we're using groovy on this course so type 1 then hit enter finally we need to choose a name for our project Gradle defaults to the name of the directory we're in so hit enter to accept the default it says build successful so that's it we now have a simple Gradle project called get going with Gradle let's try interacting with the project by running a Gradle task remember we should always use the Gradle wrapper to run Gradle tasks so type dot slash Gradle w space help and hit enter remember if you're on Windows it's going to be Gradle w dot bat spacehelp this gives us some useful getting started information it says to see a list of available tasks run Gradle W tasks let's try that type dot slash Gradle w space tasks and hit enter this prints out all the tasks we can run in our project because the project doesn't build anything yet there isn't much very useful we can do that said you can see listed here the init task and tasks tasks we've just run just for fun pick one of the help tasks at random and run it here I'm going to run the dependencies task which correctly says there are no dependencies in this project let's just clear the screen now let's have a look at the different files in our project that were created by Gradle type ls-l and hit enter we can see the build.gradle main build file the grader directory containing the Gradle wrapper configuration the two Gradle wrapper Scripts and the settings.gradle file let's have a look inside build.gradle type cat space build.gradle and hit enter there's nothing here except a comment for now but it's ready for us to add some build logic later now let's look inside the settings.gradable file type catspace settings.gradle and hit enter on the last line of the settings file you can see the name of this project has been set to get going with gradual because that's the name we selected in the setup wizard let's take a look at any hidden files or directories so type LS space Dash L A and hit enter the files and directories which start with a DOT are hidden we've got two files dot get attributes and Dot get ignore and our directory.gradle as I mentioned before the dot Gradle directory is used internally by Gradle and shouldn't be committed into Version Control the dot get ignore file has been created automatically by gradual let's take a look inside type cat space dot get ignore and hit enter we can see here that there are two directories being ignored we have the dot Gradle directory which we've just seen and also a build directory where your Project's build outputs go we'll talk about that later the build directory doesn't exist yet because we haven't built anything yet because these files are in the dot git ignore file they won't get committed when we commit this project to a git Repository speaking of which the last thing to do now is to commit this project into Version Control we need to initialize this directory as a git repository so type getting it and hit enter let's get all the files ready to be committed so type git space add space Dot and hit enter now type git space status and hit enter to see what files are staged for commit notice that everything is going to be committed except for the dot Gradle directory let's commit all of this so type git space commit space m and with a message of initialized project then hit enter good work you've just created your first Gradle project and committed it into Version Control before we finish this lesson here's a quick summary of what you've just achieved you've used Gradle init to initialize a basic Gradle project using the setup wizard remember the options you selected were a basic project using The Groovy language for the build script using the project name from the directory name of get going with Gradle you then initialize the project as a git repository committed only the relevant Gradle files and directories in diversion control that's all I wanted to cover in this lesson you're making good progress I look forward to joining me in the next lesson welcome back and in this lesson we're going to talk about one of the most common use cases for Gradle which is to create a Java project let's get right into it let's first put Gradle aside and think about what are the most important requirements we have for building a Java project once we understand this I'll show you how gradual handles each of these requirements first in a Java project we have Java classes files with the dot Java extension that need to be compiled into executable.class files these dot class files are then executed in our deployment environment to run our application so our first requirement is to compile Java classes into dot class files second we may have additional resources other than Java classes that need to go into our Target environment this could be text files images or anything else which needs to live alongside the code all of this needs to be properly managed third we need a mechanism to easily package the compiled classes and resources into a Java jar file a jar file is just a zip file in a specific format that Java recognizes and it's a lot easier to manage than handling directories and files the next thing is we'd like a mechanism to easily run tests against our code importantly though tests shouldn't be packaged into the final build artifact as they're not required to execute the application finally it would be great to have a way to manage dependencies in our Java project rather than writing code from scratch in every project we often pull in other libraries to help do the heavy lifting some popular Java libraries include Apache Commons and spring boot if we had a way to define all these dependencies with their versions that would be super helpful of course there may be other requirements with more complex projects but this list provides a good starting point so how can Gradle help with this it turns out that it's extremely simple to set up a Java project with gradual all you have to do is apply the Java plugin which adds all the functionality you'd need to meet all the requirements we just talked about remember in an earlier lesson when we were talking about plugins in the build.gradable file to apply the Java plugin all you have to do is add an entry into the plugin section of build.gradle like this once the plugin has been applied your Gradle project will be configured in a certain way and some additional tasks will become available that's generally what plugins do they add new functionality to your project the Java plugin is one of the core Gradle plugins that means it's important enough that it's bundled up with the Gradle distribution and maintained by the Gradle team in the rest of this lesson we're going to look at what functionality the Java plugin brings to a project and what specific structure it expects a project to have a first requirement for a Java project was to compile classes the Java plugin allows us to do this through a task called compile Java you can run this like you would any Gradle tasks with DOT slash Gradle w space compile Java this task will use whatever Java installation is set up in your environment to compile your projects.java files into dot class files these dot class files get output into the Gradle build directory which is the directory where any generated build out puts some grade will get created here's an example showing that if I had a Java class my first class in a package called com.tom Gregory then the compiled class would get output into the build directory with this specific directory structure don't worry about the details of the directories for now because I'll explain the structure in full later in this lesson what's important to remember is just that the compiled classes go into the build directory the next requirement for a Java project was to manage resources you guessed it the Java plugin allows us to do this through another task the task is called process resources you run this task using dot slash grade or w space process resources and the task will look in specific directories in your project which have been marked as resources directories and copy the contents into the build directory the reason it's called process resources is that it can do some additional processing along the way such as finding and replacing strings here's an example showing that if I had a text file called superimportant.txt in a Resources directory when I run the process resources task the text file would get copied into the build directory with this specific directory structure I'll go over the directory structure in more detail but just know for now that process resources copies resources into the build directory the next requirement for a Java project was to package our compiled classes and resources into a jar file unsurprisingly there's another gradual task for this can you guess what it's called that's right the Java plugin adds a jar task and you run this using dot slash Gradle w space jar the jar task takes all the compiled classes and resources from the build directory and adds them to a jar file the name of the jar file is the project name Dash version dot jar so it uses the build metadata we saw in an earlier lesson defined in build.gradle and settings.gradle files here's an example that shows if we had a project with classes and resources the jar tasks which package them up into a jar file in the build slash Libs directory you'll be able to try out building a jar file yourself in the next lesson which is a practical all about creating your first Java Gradle project the next requirement for a Java project was to easily run tests that's achieved with a task called test which you run using a DOT slash grade or w space test and what this does is to compile your test code process any test resources you might have then run the tests the other nice thing it does is to produce a pretty test report in the build directory here's an example the report tells us what's passed and what's failed the final requirement we had for a Java project was to easily Define dependencies the way dependencies are managed in Gradle is in the dependencies section of the build.gradle which we talked about briefly in an earlier lesson as a reminder the dependency configuration looks like this here we have two dependencies defined one for Apache Commons Lang 3 and 1 for junit 5. importantly when you define dependencies you must Define the group the name and the version separated by a colon this gives Gradle enough information to be able to go and find the dependency in whatever repositories you've configured and download it when you declare the dependency it goes into a specific dependency configuration implementation is for any dependencies required during compilation of your code or during execution of your code test implementation is similar but is for dependencies required during compilation or execution of your tests it's important you pick the correct dependency configuration because they're used to generate the Java class path the class path is used by Java so it knows about all the classes required during code compilation or execution this means when the compile Java Gradle task uses Java to compile your classes the class path will need to include all the dependencies required for compilation in this lesson we've talked about how the Java plugin takes classes and resources processes them in some way and outputs generated files into the build directory the last topic I want to discuss is the default project layout that the Java plugin expects the standard layout means it knows where to find things Source slash main Java is where the Java plugin expects to find classes within here you'd have packages and Java classes Source slash main slash resources is where it expects to find resources Source slash test slash Java is where it expects to find test classes and lastly Source slash test slash resources is where it expects to find test resources and as is normally the case with Gradle these locations are configurable but it's almost always best to go with a default layout if you can because it's a standard that people expect to see it's also the same layout that the popular build tool Maven uses on the right hand side I'm going to show where the classes or resources on the left end up in the build directory remember that the build directory contains all the Gradle build outputs and importantly doesn't get committed into Version Control so classes go into build slash classes slash Java main resources go into build slash resources slash main test classes go into build slash classes slash Java test and test resources go into build slash resources slash test you don't need to remember all these destination details but it should help you navigate your way around the build directory if you ever need to as a quick summary before we finish the Java plugin initializes a project as a Java project which means it adds tasks for compile Java process resources jar and test dependencies can be defined as implementation or test implementation and they ultimately end up on the generated Java class path always use the standard project layout so the Java plugin knows where to find files hopefully you found this useful I know it's very theoretical at this point which is why in the next lesson we're going to jump straight into a practical where you'll create your first Java project with gradual I look forward to you joining me in the next lesson welcome back to this practical lesson where we'll take everything from the theory lesson about how Gradle works with Java and apply it to a realistic real-world scenario let's get right into it so at this point of the course you've already got practical experience of creating a basic Gradle project and running tasks you should also be familiar with the Gradle Java plugin and the ways in which it configures a project now it's time to take all of that and cement your knowledge by putting it into practice we're going to be creating a Gradle build for a simple Java application if you don't have any knowledge of java coding that's not a problem because I'm going to be supplying all the code you'll need now this application is very simple and it will take as an input a language code such as en for English or ES for Spanish output the word hello in that language assuming it holds a translation for it here are some example inputs and outputs if I input en for English the application will print hello if I input es for Spanish the application will output Ola I know it's amazing stuff this could seriously be a competitor for Google translate don't you think we're built on top of the project you created in the previous practical lesson creating your first Gradle project if you don't have that project then please go and complete that practical so you're in the right position to start this lesson and as usual you'll find step-by-step instructions in the notes below this video you'll also need to copy some code Snippets from there once we get into the main part of this lesson we're going to start off with a project exactly as we left it in the previous practical lesson we'll be making several changes such as editing files creating new directories and creating new files if you want to do that on the command line that's fine or you can use a text editor or IDE that you're comfortable with I'm going to be using IntelliJ IDEA as a simple editor that allows me to browse and edit the file structure I'm not going to be using any of the IDE support for Gradle as I want you to understand Gradle from the foundations all of the commands we run will be interacting with Gradle directly on the command line so here's the project structure as we left it in the previous practical lesson as a quick recap we've got the get ignored dot Gradle directory the gradual directory containing the wrapper configuration the build.gradle build script and the two Gradle wrapper Scripts and the settings.gradable file where our project name is defined we've also got two git files and also a DOT idea directory which was added automatically because I'm using IntelliJ IDEA if you're using a different editor you won't have that so don't worry about it first off we're going to add the Java code for this language application we've got some main application code to add and also some test code let's add the main application code first remember this goes into a directory called Source slash main slash Java so let's go ahead and create that directory Source slash main slash Java this is where Gradle will look for Java classes when we run the compel Java task let's create a Java package in here ready for our code create another directory and call this one com slash Tom Gregory slash language app inside that new directory we'll create a Java class so create a file and call it say Hello dot Java and open it for editing now I need you to go to the notes for this video and copy the whole contents of the say hello.java class and paste it into the file in your project this is all the code for the application we're not going to go into all the details of how it works because this isn't a Java course but as a quick overview we've got a main method that takes in some arguments and the first argument the one with index 0 we expect to be the requested language we take that language and add a DOT txt onto the end of it and look for that file in the resources on the Java class path the rest of this code is to do with opening that resource and reading it on the last line here we print out the contents of the first line of the file this means you can request a language and if there's a file present in the resources the application will print out the contents of that file speaking of which we should go and create some files now for the different languages if you remember that resources go into Source slash main resources we just need to create a new directory under Source slash main called resources let's do that now let's create some files for different languages create a file called en.txt and in the file we'll put hello with an exclamation mark for emphasis then we'll create another file es.txt and in this file enter Ola which from my Spanish lessons I know means hello in Spanish this is all the code and resources we need for this application now we just need to get it built we'll do that by adding the Java plugin and a few other configurations to get to the point where we can compile the code generate a jar file and execute the application from that jar file let's close all these files then go into the build.gradle file and the first thing we'll do is remove this auto-generated comment now let's add the plugins block which is the word plugins with curly brackets inside the curly brackets we'll declare that we want to apply the Java plugin so add ID space and then in single quotes Java with just this one change we've now got a whole load of new functionality in our Gradle build let's go to the command line and type dot slash Gradle w space tasks and hit enter all the tasks listed under build tasks have been added to the project by the Java plugin if you remember back to the theory lesson we were talking about the compile Java and process resources tasks you don't see them here because actually they get run automatically when you run the classes task or to put it in Gradle terminology the classes task depends on compile Java and process resources Bridle only shows you the high level tasks by default but if you want to see all the tasks you can run dot slash grade or w space tasks dash dash all under other tasks you can now see compile Java and process resources let's see what happens if we run compile Java so run dot slash Gradle w space compile Java you should notice that build directory has now been created inside there you should have a build slash classes slash Java slash main directory and in there gets created compiled java.class files in the correct package structure if you can see say hello.class then everything's working properly let's do the same for process resources so run dot slash Gradle w space process resources you'll have a new directory build slash resources slash main and in there you should see the text files we created earlier en.txt and es.txt that's great now let's try to generate a jar file so run dot slash Gradle w space jar and hit enter you should now have a jar file in build slash Libs called get going with gradle.jar notice that there's no version included that's because we haven't specified a version in our build.gradable we're going to try to run the application now using the jar file we just created type or copy the command Java space Dash jar space build Libs slash get going with gradle.jar space en and the en is a command line argument requesting the English language and hit enter you'll see an error saying that no main manifest attribute was found this means that Java doesn't know what class within the jar file to run even though there's only one class we have to add what's called a manifest file specifying that say hello is the main class fortunately that's really easy with the Gradle Java plugin we can configure the jar file in the build.gradle with this snippet of code so just paste it in making sure that the class package and name matches the main class you created this configuration tells the Gradle jar task to additionally create a manifest file with this main class attribute so that Java knows that say hello is our main class we need to build the jar file again so run dot slash Gradle w space jar now rerun the Java command that failed earlier and you should see the text hello output just to prove that it's all working correctly run the same Java command but replace en with es for Spanish it should now say hola awesome you just built your first Java application with Gradle we're not quite done yet though as we need to add a test to make sure that this powerful application behaves as expected tests live in Source slash test slash Java so under Source create a new directory test slash Java we're going to create a test for say hello.java So within this directory we'll create the same package structure so create directories Tom Gregory language app now add a file in here and call it say hello test dot Java copy the say hello test.java class contents from the notes below this video and paste it into the new file the test class uses the junit testing framework to run a very simple test that just makes sure that the say hello class executes without throwing any errors let's try running the test with the test Gradle task this will compile the test code process any resources then run the tests themselves type or paste the command dot slash Gradle w space test and hit enter okay we've got an error here saying that it can't find the org.junit.jupiter.api package which is the junit code we need to run the tests this has happened because we haven't declared any dependency on this Library so when our test class is being compiled it's missing junit from the class path we'll fix this by adding a dependency configuration block to our build.gradle after the plugins so I'm just going to close the test and after plugins type or copy in this dependency configuration block from the nodes this adds a dependency to the test implementation dependency configuration which means the dependency will end up on the class path during test compilation we've declared the dependency with the group colon name colon version structure for junit 5. we also need to add a repositories configuration so that Gradle knows where to download this dependency from type or copy in the repositories configuration before the dependencies configuration this tells Gradle to use the maven Central repository for dependencies run the same command that failed again dot slash Gradle w space test and you should see a successful build let's double check the test report which is located in build slash reports slash tests slash test and index.html open it in a browser so what's going on here well since junit version 5 is still in the process of being adopted from junit 4 an additional configuration is required to enable it so I'm just going to close index.html I'm back in build.gradle just after dependencies type or copy in this test configuration which configures tests to use the junit 5 platform let's run dot slash Gradle w space test again build successful let's open the test report again you should now see that one test has run and we have a 100 success rate it looks like everything is working correctly all that's left to do now is to commit this project run git space ad space dot to get everything ready to commit and then type git space status you should see all the files we've just added and changed so let's commit these by running git space commit space m with a message create Java project for language app and hit enter that's all I wanted to cover in this lesson hopefully now you've got a good feel for how to create build and test Java projects with Gradle there are some important points that are still left to cover so we'll be coming back to this project again in a later lesson to explore some other Gradle tasks such as build and assemble I look forward to joining me in the next lesson welcome back in this lesson we're going to cover three key groovy language features which will help you to properly understand Gradle build files let's get right into it as you know by now groovy is a scripting language built to run in the Java virtual machine this means it's based on Java and runs in Java groovy is an extended version of java that has some nice language features that can make writing code quicker Gradle uses these features to make defining your build very concise and we'll be covering them in the rest of this lesson however you can write Java code directly in groovy and therefore in the build.gradle this is useful if you already have some knowledge of java as you'll be able to easily add certain functionality to your build script as an example here's a groovy script that defines three names in a list sorts them then prints the result this is the same example in Java it's a bit more code but it might be more familiar to you both of these code Snippets produce exactly the same result when executed in groovy so when you're working with Gradle bear in mind that you can write Java code in groovy when you're trying to understand a Gradle build script it's worth remembering that in groovy brackets are optional when cooling a function well actually brackets are optional if the function has one or more arguments that's why on the previous slide we could call printerland without brackets printerland without brackets is equivalent to printerland with brackets this feature is used by the Gradle build script in many surprising ways for example do you remember the dependencies configuration we defined in build.gradle in the Practical lesson it looked like this and it's actually just a function called dependencies without any brackets this is how the function signature looks don't worry about the argument for now as we'll cover that in the next slide just remember that whenever you see something that looks a bit magic in a Gradle build script it may just be a function without brackets the same dependencies declaration could be written with brackets like this if we wanted to so when you're working with Gradle bear in mind the brackets are optional groovy supports closures the simplest way to describe a closure is as a function which can be treated like a variable and executed when required here's a simple example of a groovy closure I'm defining a variable amazing calculator which is assigned a closure the closure is defined between curly brackets the first part of the closure is optional but if provided defines the list of arguments that should be passed to the closure here we're passing two variables A and B the second part is the code that gets executed here we're adding together the two arguments A and B by default the result of the code gets returned from the closure when it's executed this means when the closure is executed with the values two and three it returns five closures are very useful as they allow us to write concise code without having to Define named functions Gradle makes heavy use of groovy closures in its build script is the dependencies configuration we saw in the previous Slide the bit between the curly brackets is just a closure without any arguments the closure is being passed to The Groovy dependencies function for processing so when you're working with Gradle bear in mind that whenever you see curly brackets then it may just be a closure being passed to a function you may be wondering at this point why you need to know about these groovy language features isn't it enough just to know how to write a Gradle build script while that may be enough for the basics I think this knowledge will help fast track your Gradle learning for these reasons first if your IDE supports gradual you'll be able to browse the Gradle source code directly and understand what functions are available to you in your build script this is often quicker than referring to documentation for example here's a snippet of one of the main Gradle interfaces called project containing the dependencies function we've just been looking at and many more all of these functions can be called directly from build.gradle second with this knowledge you'll be able to make better use of some Advanced Gradle features such as writing your own plugins we won't be covering these topics in this introductory course but I want to set you up with the fundamentals to allow you to continue your learning should you want to that's everything I wanted to show you here hopefully now you've got a better understanding of the grade or build script and what groovy language features it makes use of I look forward to joining me in the next lesson welcome back in this lesson you're learning more detail what the Gradle task graph is what it looks like in a Java project and how you can make the best use of it in your day-to-day work let's get right into it we've already discussed in a previous lesson how tasks can have dependencies on other tasks dependency on another task means that the other task gets run first now to avoid any confusion it's worth noting that task dependencies are a completely separate concept from the dependencies you set up for compiling your code such as junit let's use as an example some of the tasks added by the Java plugin the build task depends on the assemble and check tasks this means that when you run dot slash Gradle w space build assemble and check get run first I know we haven't used any of these tasks yet in this course but don't worry because in a moment you'll see them in action now the interesting thing here is that the build task itself doesn't do anything when it's run it's only there to aggregate both the assemble and check tasks together assemble handles building your project including creating artifacts such as jar files and check handles testing your project the build task using task dependencies make sure that both assemble and check get run that's really nice as it means if you ever need to build and test a whole project you can just run a single task build to do everything so that was just three of the tasks added by the Java plugin there are lots more so let's take a look at the complete task graph for these tasks here it is and I know there's quite a lot to look at here but don't worry as we're going to step through this bit by bit the lines that you see connecting a task to the left to task to the right imply dependency on the task to the right so for example build depends on check you've already got practical experience of some of these tasks which I'm highlighting with a rectangle to the left of the task name this includes jar compile Java process resources and test these tasks are highlighted in green which I'm using to show tasks which actually perform an action when they're run for example jar creates a jar file compile Java compiles classes process resources well processes resources and test runs tests let's take a look at the classes task which I'm highlighting in blue now this task doesn't perform any action itself when it's run merely Aggregates compile Java and process resources using task dependencies so I'll use blue to highlight any aggregate tasks moving up the tree assemble is another aggregate task which when run causes the jar tasks to run which in turn runs classes which runs compile Java and process resources you get the idea let's focus now on the tasks under the test task you notice we have the same compile Java process resources and classes tasks the reason for that is to ensure that when we run the test task our main application code has been properly compiled and resources processed moving down again these three tasks are duplicated again under compile test Java compile test Java itself is the task which when run compiles or your test code and similarly process test resources processes all your test resources above all these we have the test classes task which is another aggregate task which depends on compile test Java and process test resources and above this is the test task which when run first ensures that both the main code and the test code are built before running the tests themselves above test is check another aggregate task which just depends on test and at the very top level is build another aggregate task which as I mentioned before can be used to build and test everything in your project now that was a lot of information which thankfully you don't need to remember in its entirety I'm going to highlight five key Gradle tasks for you to remember which will help you using Gradle in your day-to-day work build as mentioned can be used when you just need to build and test the whole project assemble and jar you can think of as equivalent for now can be used when you only need to assemble the project without testing it finally check and test which you can think of as equivalent can be used to test your code without assembling it you might be wondering at this point why you wouldn't just run build all the time well for medium to large projects they can take some time to build so picking the specific Gradle task for what you need to accomplish can save you some time for example if you just need to test your code change then you could run the check task rather than build this may save you some time as check doesn't depend on the jar task so no jar will get created likewise if you just need to build your project including the jar file without testing your changes you could run the assemble task now I'm going to jump back into the get going with Gradle project as we left it in the previous practical lesson demonstrate a few of these important Gradle tasks before we get started we're going to run a task which we haven't talked about yet called clean this is a simple task which deletes the build directory normally you won't need to run this very often but I want to run it now to ensure we start in a fresh State and I can see what each of the tasks we're going to run does so let's run dot slash Gradle w space clean and you'll see now that I no longer have a build directory first important task to run is assemble which from the previous slide you learned will compile your code process resources and build a jar file so let's run dot slash Gradle w space Assemble [Music] taking a look at the newly generated build directory we can see we have compiled classes in classes slash Java slash main resources in the resources slash main directory and also a jar file in the libs directory so assemble is great for generating all your build artifacts in one go notice that we don't have any test reports generated as assembled doesn't run the tests now let's delete the build directory Again by running dot slash Gradle w space clean the next important task to run is check from the previous slide you know that this task compiles the main code processes the main resources compiles the test code processes the test resources and actually runs the tests too let's run dot slash Gradle w space check in the build directory we have both the classes slash Java slash main directory and also classes slash Java test this is because Gradle has compiled Main and test classes in the Resources directory we still only have the main resources but if we had any test resources in this project they would also appear here too we also have a reports directory containing the test reports since our tests were also executed notice that importantly we don't have a Libs directory or any jar file as the check task doesn't depend on the jar task so check is a task to run when you just need to run the tests without assembling everything in your project I'm going to delete the build directory once more with DOT slash Gradle w space clean the final important task to try out is build which as you know from the previous slide depends on the two tasks we've just run assemble and check let's run dot slash Gradle w space build [Music] in the build directory we can see that we have both Main and test code we have the processed resources we have a jar file in the libs directory and we have test reports showing that the tests ran so build is the task to run when you just need to assemble your whole project and run all the tests that was quite a lot of information in just a few slides so I just want to summarize the key takeaways here first remember that some tasks actually perform an action and some are just aggregate tasks aggregate tasks are helpful to combine multiple tasks together using task dependencies the Gradle plugin creates many Gradle tasks but we only really need to remember the high level tasks such as assemble and jar which both do the same thing of compiling your code and building a jar file check and test which do the same thing of testing your code and lastly build which does both an assemble and a check hopefully now you've got a better understanding of all the different tasks used in a Java project in gradual and how they fit together that's everything I wanted to cover so I look forward to joining me in the next lesson congratulations on getting this far in the course you've done really well and now have knowledge of the Gradle fundamentals as well as practical experience in creating Gradle projects from scratch this was an introductory Gradle course giving you the knowledge to work with simple Java projects in your day-to-day work to go beyond basic projects and make sure you implement Gradle effectively I suggest you continue your learning to cover additional topics such as using the other dependency configurations in Java projects which help build your project more efficiently learn to locate and configure tasks to get your project built and tested exactly how you want running Java applications from Gradle with the application plugin building spring boot projects in grade almost effectively what the difference is between building applications and libraries and what you need to do differently for each one and using the Java tool chain to ensure your applications always build consistently with the same Java version the good news is that there are plenty of resources available online to cover these topics such as those over at docs.gradle.org on the other hand if you'd like to continue learning right here with me then the Gradle hero course gets you to Mastery of java projects in Gradle as fast as possible if you found this content helpful Gradle hero multiplies that by a factor of 10 giving you everything you need to master every aspect of the Gradle build script in groovy and kotlin never feel intimidated by Gradle build script again Take Back Control of your Gradle build and finally get your team working more effectively and ensure your grade will build scales with the growth of your application by implementing multi-project builds and custom tasks and plugins in fact this course was requested by Engineers like you who wanted something to take them to the next level having completed this introductory course to learn more follow the link in the notes and continue your journey today thanks for joining me on this course and I'm sure we'll speak again soon now it's time to put everything you've learned into practice
Info
Channel: Tom Gregory
Views: 7,670
Rating: undefined out of 5
Keywords:
Id: So0j4RnoKkU
Channel Id: undefined
Length: 70min 1sec (4201 seconds)
Published: Tue Oct 18 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.