Spring Boot Hello World
Creating Hello World
Creating a Gradle Project
$ mkdir spring-boot-hello-world
$ cd spring-boot-hello-world
$ gradle init
Create the Java source directory.
$ mkdir -p src/main/java/sample/springboot
Writing the Source Code
buildscript {
repositories { mavenCentral() }
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.6.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'org.springframework.boot'
repositories { mavenCentral() }
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
}
jar.baseName = 'spring-boot-hello-world'
@SpringBootApplication
public class Main {
public static void main(String[] args) {
try (ConfigurableApplicationContext ctx = SpringApplication.run(Main.class, args)) {
Main m = ctx.getBean(Main.class);
m.hello();
}
}
public void hello() {
System.out.println("Hello Spring Boot!!");
}
}
Running the Application
Run with Gradle:
$ gradle bootRun
Or build and run the JAR:
$ gradle build
$ java -jar build/libs/spring-boot-hello-world.jar
Both methods print:
Hello Spring Boot!!
Explanation
The Spring Boot Gradle plugin provides the bootRun task and executable JAR packaging. SpringApplication.run() starts Spring Boot.
@SpringBootApplication combines:
@Configuration: Java-based Spring configuration.@EnableAutoConfiguration: Automatic Spring configuration based on dependencies.@ComponentScan: Automatic Bean registration by scanning packages for components.
The second argument to run() passes command-line arguments.