JDK 17
Spring Boot 2.7.0
参考URL https://spring.io/guides/gs/rest-service/
https://start.spring.io/ でプロジェクトを作成する。
zipファイルを解凍し、EclipseでImport Projects → Exsisting Maven Projects
pom.xmlへdependencyを追加する。
追加しないと「The import org.springframework cannot be resolved」エラーが出る。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
デバッグライブラリを追加する場合。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
JSONマッピングクラスを作成する。
フィールドがキー、戻り値がバリューのJSONがマッピングされる。
package hellorestfultest;
public class Hello {
private String hello = "Hello World";
public String getHello() {
return hello;
}
}
RESTコントローラーを作成する。
package hellorestfultest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public Hello hello() {
return new Hello();
}
}
デバッグ実行する。
「…Application.java」クラスファイルを右クリック → Debug As → Java Application
curlで実行結果を確認する。
curl http://localhost:8080/hello
{"hello":"Hello World"}
オブジェクトマッピングをしない場合はStringを返せば同じ結果が得られる。
package hellorestfultest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public Class HelloController {
@GetMapping("/hello")
public String hello() {
return "{ \"hello\" : \"Hello World\" }";
}
}