Spring Boot Web アプリケーションの起動
Web アプリケーションの起動
ここでは Spring Boot - Hello World を修正する。
Web アプリケーションの依存関係変更
build.gradle
dependencies {
- compile 'org.springframework.boot:spring-boot-starter'
+ compile 'org.springframework.boot:spring-boot-starter-web'
}
Web アプリケーションを作成する場合は、spring-boot-starter-web モジュールを使用する。
基本的に Spring MVC を使用して Web アプリケーションを作成することになる。
起動方法の変更
サーバー起動後にコンテナが終了してしまうため、try-with-resources 文を使用しないように変更する。
src/main/java/sample/springboot/Main.java
package sample.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
Spring MVC コントローラークラス
Web API のエントリーポイント(Entry point)となるクラスを作成する場合、クラスに @RestController を付与する。
Web API ではなく MVC の C となるコントローラーが必要であれば、@Controller アノテーションを付与する。
@RequestMapping でパスおよび HTTP メソッドをマッピングする(おおよそ JAX-RS に似た雰囲気である)。
src/main/java/sample/springboot/web/HelloController.java
package sample.springboot.web;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method=RequestMethod.GET)
public String hello() {
return "Hello Spring MVC";
}
}
アプリケーションの実行
Gradle で実行
$ gradle bootRun
(省略)
> :bootRun
curl でテスト
$ curl http://localhost:8080/hello
Hello Spring MVC