- Create a empty directory first.
- Navigate to the directory and run the command gradle init –type java-application
Contents of the directory are :
Now edit the contents of build.gradle as per below :
plugins {
id 'java'
id 'org.springframework.boot' version '2.0.5.RELEASE'
id 'io.spring.dependency-management' version '1.0.7.RELEASE'
}
repositories {
jcenter()
}
dependencies {
implementation 'com.google.guava:guava:28.0-jre'
testImplementation 'junit:junit:4.12'
implementation 'org.springframework.boot:spring-boot-dependencies:2.0.5.RELEASE'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
components {
withModule('org.springframework:spring-beans') {
allVariants {
withDependencyConstraints {
it.findAll { it.name == 'snakeyaml' }.each { it.version { strictly '1.19' } }
}
}
}
}
}
bootJar {
mainClassName = 'GradleDemo.App'
}
task runJar{
dependsOn 'assemble'
dependsOn 'jar'
doLast{
javaexec {
main="-jar";
args = [
"build/libs/"+rootProject.name+".jar"
]
}
}
}
App.java as per below
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package GradleDemo;
import org.springframework.boot.SpringApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
HelloGradleController.java parallel to App.java like below :
package GradleDemo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController("/")
public class HelloGradleController {
@GetMapping
public String helloGradle() {
return "Hello Gradle!";
}
}
AppTest.java like below :
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package GradleDemo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@AutoConfigureMockMvc
public class AppTest {
@Autowired
private MockMvc mvc;
@Test
public void helloGradle() throws Exception {
mvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(content().string("Hello Gradle!"));
}
}
Now run the task runJar in command prompt