第5章 JSON レスポンスを返すように GreetingController を設定する
Spring Web サンプルの設定時に自動的に生成される GreetingController は、テキスト文字列をレスポンスとして返す単純なエンドポイントです。より複雑なアプリケーションでは、レスポンスを JSON 形式で返すように REST コントローラーを設定しなければならない場合があります。以下の例は、JSON コンテンツを返すように Spring RestController を設定する方法を示しています。
手順
以下の例のように、
GreetingControllerクラスを展開します。拡張されたクラスは、greeting および名前が含まれる JSON 形式のレスポンスを返します。Spring Web からPathVariableアノテーションクラスをインポートして、設定が正しく機能することを確認する必要があります。src/main/java/org/acme/spring/web/GreetingController.java
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/greeting") public class GreetingController { @GetMapping public String hello() { return "hello"; } @GetMapping("/{name}") public Greeting hello(@PathVariable(name = "name") String name) { return new Greeting("hello " + name); } public static class Greeting { private final String message; public Greeting(String message) { this.message = message; } public String getMessage(){ return message; } } }
REST エンドポイントに変更を加える場合は、REST エンドポイントのユニットテストが含まれるクラスファイルも更新する必要があります。
src/test/java/org/acme/spring/web/GreetingControllerTest.java
package org.acme.spring.web; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @QuarkusTest public class GreetingControllerTest { @Test public void testHelloEndpoint() { given() .when().get("/greeting/quarkus") .then() .statusCode(200) .body("message", is("hello quarkus")); } }Quarkus で Spring Web 互換レイヤーを使用すると、com.fasterxml:jackson.core 依存関係がアプリケーションのクラスパスに自動的に追加されて設定される点に留意してください。