Spring Boot Hello World

Hello Worldを作成する

Gradleプロジェクトを作成する

$ mkdir spring-boot-hello-world
$ cd spring-boot-hello-world
$ gradle init

Javaソースディレクトリを作成します。

$ mkdir -p src/main/java/sample/springboot

ソースコードを作成する

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!!");
    }
}

アプリケーションを実行する

Gradleで実行します。

$ gradle bootRun

またはJARをビルドして実行します。

$ gradle build
$ java -jar build/libs/spring-boot-hello-world.jar

どちらも次の内容を出力します。

Hello Spring Boot!!

説明

Spring Boot Gradle pluginはbootRunタスクと実行可能JARの作成機能を提供します。SpringApplication.run()でSpring Bootを起動します。

@SpringBootApplicationは次のアノテーションをまとめたものです。

  • @Configuration: JavaベースのSpring設定。
  • @EnableAutoConfiguration: 依存関係に基づく自動設定。
  • @ComponentScan: コンポーネントを検索してBeanを自動登録。

run()の第2引数はコマンドライン引数を渡します。

ソースコード