24
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Spring BootでAPIを作るときの最小構成を図解してみた

Last updated at Posted at 2025-12-12

はじめに

Spring Boot を触りはじめたころ、
「Controller と Service の違いって何?」
「Repositoryって急に出てくるけど、どこで使うの?」
みたいに、基本の流れの理解に時間がかかっていました。

あとから「これ、最初に誰かに分かりやすく教えてほしかった…」と
思うことがあったので、初めての記事は API を作るときの最小構成 を、できるだけシンプルにまとめてみました。

Spring Boot を触り始めたばかりの人が、
「こういう流れで動いてるんだな」と直感的に掴めるような内容になっています。

  • Spring をこれから学ぶ人
  • なんとなく雰囲気でコードを書いてきた人
  • 層構造をイメージで理解したい人

そんな方に読んでもらえたら嬉しいです。


📦 プロジェクト構成(最小構成)

ディレクトリ構成(最小構成) src
└ main
└ java
└ com.example.demo
├ controller
│ └ SampleController.java
├ service
│ └ SampleService.java
├ repository
│ └ SampleRepository.java
└ DemoApplication.java

🧩 各レイヤーの役割をざっくり説明

Controller / Service / Repository の説明

1. Controller(入り口)

  • HTTP リクエストを受け取る
  • どの API を呼び出すか判断する
  • 返すレスポンスを決める
@RestController
@RequestMapping("/api/sample")
public class SampleController {
    private final SampleService service;

    public SampleController(SampleService service) {
        this.service = service;
    }

    @GetMapping
    public String hello() {
        return service.getMessage();
    }
}

2. Service(ビジネスロジック)

  • 実際の処理を書く層
  • DB の操作や計算など、ビジネスロジック全般を担当
  • Controller と Repository の中継ぎ・調整役
@Service
public class SampleService {
    public String getMessage() {
        return "Hello from Service!";
    }
}

3. Repository(DBアクセス担当)

  • DBとやり取りする層
  • Spring Data JPA を使うと、インターフェイスだけで CRUD が自動生成される
  • ※CRUD (C:Create(作成)、R:Read(読み取り)、U:Update(更新)、D:Delete(削除))
@Repository
public interface SampleRepository extends JpaRepository<SampleEntity, Long> {
}

4. Application(起動ポイント)

  • Spring Boot アプリのエントリーポイント
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

図解:API の流れ

  • Controller → Service → Repository の流れを意識することで、コードが整理しやすく、後からの拡張もラクになります

🔚 まとめ

  • Spring Boot の API は Controller / Service / Repository の 3 層構成が基本
  • シンプル構成でも実務レベルの API を作れる
  • まずは “動くもの” を作って、徐々に理解・拡張すれば OK
24
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?