Thursday, May 3, 2018

Your First Gradle Project with Intellij Idea

To create a new Gradle project go to File->New->Project and it will open the following New Project window.




Select Gradle form left menu and check Java as additional libraries and frameworks. In addition to that, you need to select the run time java version as the project SDK.
Click on Next button and select the Group Id, Artifact Id and Version values as below.
The Artifact Id and the Version parameters are combined to generate the name of the deployable(jar,war etc...). However the Group Id is required only if we are planning to deploy the output in the maven repository which can be use as a dependency to another project. 


Click on the Next button and check the 'Use Auto Import' in the following window. Keep the other parameters as it is.

The importance of Check icon the 'Use Auto Import' is Once we add or remove dependency from build.gradle file, those changes will automatically reflect to the IDE. 
Click on the Next button and select the Project Name, Project Location and then click on the Finish button.  
The project will be created as below.
However we can't see the folder structure. To generate the source folder, go to the File->Settings->Build,Execution,Deployment->Build Tools->Gradle. In the below window, check the Use auto-import and Create directories for empty content root automatically.


Click on the OK and you can find the project folder structure has been created as below.

Then click on the java folder and create a simple java class as below.


 public class HelloWorld {  
   public static void main(String[] args) {  
     System.out.println("Hello Gradle............");  
   }  
 }  

In addition to that, open the build.gradle file and select the correct version of java run time for the sourceCompatibility.

 plugins {  
   id 'java'  
 }  
 group 'com.randika'  
 version '1.0-SNAPSHOT'  
 sourceCompatibility = 1.7  
 repositories {  
   mavenCentral()  
 }  
 dependencies {  
   testCompile group: 'junit', name: 'junit', version: '4.12'  
 }  


After that we can build the project with Gradle. Open the Gradle tool window which is in the upper right side of the IDE and double click on the build button. After that you can find the "test-gradle-1.0-SNAPSHOT.jar" has been generated in the build->libs folder.
Run the jar file from its location with the below command.

 java -jar test-gradle-1.0-SNAPSHOT.jar  

However you will prompt the bellow error due to unable of finding the main class.

To overcome this issue, we can add the manifest information to the build.gradle file as bellow and build the jar again.

 plugins {  
   id 'java'  
 }  
 jar {  
   manifest {  
     attributes 'Main-Class': 'HelloWorld'  
   }  
 }  
 group 'com.randika'  
 version '1.0-SNAPSHOT'  
 sourceCompatibility = 1.7  
 repositories {  
   mavenCentral()  
 }  
 dependencies {  
   testCompile group: 'junit', name: 'junit', version: '4.12'  
 }  

You can get the below result.