spring-boot-json
JSONを使用して作成するSpring Boot
1. 概要
このチュートリアルでは、https://www.baeldung.com/rest-with-spring-series [REST service]を構築して、Spring BootでJSONコンテンツを消費および生成する方法を示します*。
また、RESTful HTTPセマンティクスを簡単に採用する方法についても見ていきます。
簡単にするために、https://www.baeldung.com/the-persistence-layer-with-spring-and-jpa [永続層を含める]ではなく、https://www.baeldung.com/the- persistence-layer-with-spring-data-jpa [Spring Data]は、これも簡単に追加できます。
2. RESTサービス
Spring BootでJSON RESTサービスを記述するのは簡単です。https://www.baeldung.com/jackson [Jackson]がクラスパスにある場合のデフォルトの意見です。
@RestController
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService service;
@GetMapping("/{id}")
public Student read(@PathVariable String id) {
return service.find(id);
}
...
__StudentController __with link:/spring-controller-vs-restcontroller[[email protected]_]に注釈を付けることで、応答本体に_read_メソッドの戻り値の型を書き込むようにSpring Bootに指示しました。 *クラスレベルで_ @ RequestMapping_もあるため、追加するパブリックメソッドについても同じです。
単純ですが、このアプローチにはHTTPセマンティクスがありません。*たとえば、要求された学生が見つからない場合はどうなりますか? 200または500のステータスコードを返す代わりに、404を返します。
HTTP応答自体の制御を強化し、コントローラーに典型的なRESTful動作を追加する方法を見てみましょう。
3. 作成
ステータスコードなど、本文以外の応答の側面を制御する必要がある場合、代わりにa__ResponseEntity_を返すことができます。
@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
Student createdStudent = service.create(student);
if (createdStudent == null) {
return ResponseEntity.notFound().build();
} else {
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdStudent.getId())
.toUri();
return ResponseEntity.created(uri)
.body(createdStudent);
}
}
ここでは、作成された_Student_を応答で返すだけではありません。 *さらに、意味的に明確なHTTPステータスと、作成が成功した場合は新しいリソースへのURIで応答します。*
4. 読む
前述したように、単一の_Student_を読みたい場合、学生が見つからない場合は404を返す方がより意味的に明確です。
@GetMapping("/{id}")
public ResponseEntity<Student> read(@PathVariable("id") Long id) {
Student foundStudent = service.read(id);
if (foundStudent == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(foundStudent);
}
}
ここで、最初の_read()_実装との違いを明確に見ることができます。
*こうすることで、_Student_ theオブジェクトがレスポンスボディに適切にマッピングされ、同時に適切なステータスで返されます。*
5. 更新
更新は作成に非常に似ていますが、POSTではなくPUTにマップされ、更新するリソースの_id_がURIに含まれる点が異なります。
@PutMapping("/{id}")
public ResponseEntity<Student> update(@RequestBody Student student, @PathVariable Long id) {
Student updatedStudent = service.update(id, student);
if (updatedStudent == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(updatedStudent);
}
}
6. 削除
削除操作はDELETEメソッドにマップされます。 URIには、リソースの_id_も含まれています。
@DeleteMapping("/{id}")
public ResponseEntity<Object> deleteStudent(@PathVariable Long id) {
service.delete(id);
return ResponseEntity.noContent().build();
}
_delete()_メソッドは実際に_Exception._をスローして失敗するため、https://www.baeldung.com/exception-handling-for-rest-with-spring [特定のエラー処理を実装]はしませんでした。
7. 結論
この記事では、Spring Bootで開発された一般的なCRUD RESTサービスでJSONコンテンツを使用および生成する方法を説明しました。 さらに、適切な応答ステータス制御とエラー処理を実装する方法を示しました。
物事をシンプルにするために、今回は永続化を行いませんでしたが、https://www.baeldung.com/spring-data-rest-intro [Spring Data REST]は、RESTfulデータサービスを構築するための迅速かつ効率的な方法を提供します。
この例の完全なソースコードはhttps://github.com/eugenp/tutorials/tree/master/spring-boot-rest[GitHubで入手可能]です。