Communitygithub.com

springboot-patterns

Spring Boot のアーキテクチャパターン、REST API 設計、レイヤードサービス、データアクセス、キャッシュ、非同期処理、ロギングを解説します。Java Spring Boot のバックエンド開発時に使用してください。REST 層、サービス、データアクセス、キャッシュ、非同期処理の構築やレビューに役立ちます。

springboot-patterns とは?

このスキルは、Spring Boot を用いたスケーラブルで本番品質のバックエンドサービスを構築するための包括的なパターン集です。コントローラー、サービス、リポジトリのレイヤー構造、Spring Data JPA によるリポジトリパターン、バリデーションと例外処理、キャッシュ、非同期処理、ロギング、フィルター、ページネーション、レート制限、外部呼び出しのリトライなど、実践的な設計パターンを提供します。各パターンには具体的な Java コード例が付属しており、Spring MVC / WebFlux での REST API 開発から、Spring Events や Kafka を用いたイベント駆動型の実装までをサポートします。また、`ForwardedHeaderFilter` を使った正しいクライアント IP の取得や、本番環境でのデフォルト設定(コンストラクタインジェクションの推奨、RFC 7807 エラー対応、HikariCP の設定など)についても詳細に解説しており、Claude Code や Cursor などの AI エージェントが Spring Boot プロジェクトのコード生成やレビューを行う際に特に有用です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/springboot-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Spring Boot 開発パターン

スケーラブルで本番品質のサービスを実現するための Spring Boot アーキテクチャと API パターン。

アクティブ化のタイミング

  • Spring MVC または WebFlux を使った REST API の構築
  • コントローラ → サービス → リポジトリのレイヤー構造の設計
  • Spring Data JPA、キャッシュ、非同期処理の設定
  • バリデーション、例外処理、ページネーションの追加
  • 開発/ステージング/本番環境向けプロファイルの設定
  • Spring Events や Kafka を使ったイベント駆動パターンの実装

REST API の構造

@RestController
@RequestMapping("/api/markets")
@Validated
class MarketController {
  private final MarketService marketService;

  MarketController(MarketService marketService) {
    this.marketService = marketService;
  }

  @GetMapping
  ResponseEntity<Page<MarketResponse>> list(
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "20") int size) {
    Page<Market> markets = marketService.list(PageRequest.of(page, size));
    return ResponseEntity.ok(markets.map(MarketResponse::from));
  }

  @PostMapping
  ResponseEntity<MarketResponse> create(@Valid @RequestBody CreateMarketRequest request) {
    Market market = marketService.create(request);
    return ResponseEntity.status(HttpStatus.CREATED).body(MarketResponse.from(market));
  }
}

リポジトリパターン (Spring Data JPA)

public interface MarketRepository extends JpaRepository<MarketEntity, Long> {
  @Query("select m from MarketEntity m where m.status = :status order by m.volume desc")
  List<MarketEntity> findActive(@Param("status") MarketStatus status, Pageable pageable);
}

トランザクション管理を行うサービス層

@Service
public class MarketService {
  private final MarketRepository repo;

  public MarketService(MarketRepository repo) {
    this.repo = repo;
  }

  @Transactional
  public Market create(CreateMarketRequest request) {
    MarketEntity entity = MarketEntity.from(request);
    MarketEntity saved = repo.save(entity);
    return Market.from(saved);
  }
}

DTO とバリデーション

public record CreateMarketRequest(
    @NotBlank @Size(max = 200) String name,
    @NotBlank @Size(max = 2000) String description,
    @NotNull @FutureOrPresent Instant endDate,
    @NotEmpty List<@NotBlank String> categories) {}

public record MarketResponse(Long id, String name, MarketStatus status) {
  static MarketResponse from(Market market) {
    return new MarketResponse(market.id(), market.name(), market.status());
  }
}

例外ハンドリング

@ControllerAdvice
class GlobalExceptionHandler {
  @ExceptionHandler(MethodArgumentNotValidException.class)
  ResponseEntity<ApiError> handleValidation(MethodArgumentNotValidException ex) {
    String message = ex.getBindingResult().getFieldErrors().stream()
        .map(e -> e.getField() + ": " + e.getDefaultMessage())
        .collect(Collectors.joining(", "));
    return ResponseEntity.badRequest().body(ApiError.validation(message));
  }

  @ExceptionHandler(AccessDeniedException.class)
  ResponseEntity<ApiError> handleAccessDenied() {
    return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ApiError.of("Forbidden"));
  }

  @ExceptionHandler(Exception.class)
  ResponseEntity<ApiError> handleGeneric(Exception ex) {
    // ログに予期しないエラーとスタックトレースを出力
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(ApiError.of("Internal server error"));
  }
}

キャッシュ

設定クラスに @EnableCaching が必要です。

@Service
public class MarketCacheService {
  private final MarketRepository repo;

  public MarketCacheService(MarketRepository repo) {
    this.repo = repo;
  }

  @Cacheable(value = "market", key = "#id")
  public Market getById(Long id) {
    return repo.findById(id)
        .map(Market::from)
        .orElseThrow(() -> new EntityNotFoundException("Market not found"));
  }

  @CacheEvict(value = "market", key = "#id")
  public void evict(Long id) {}
}

非同期処理

設定クラスに @EnableAsync が必要です。

@Service
public class NotificationService {
  @Async
  public CompletableFuture<Void> sendAsync(Notification notification) {
    // メール / SMS 送信
    return CompletableFuture.completedFuture(null);
  }
}

ロギング (SLF4J)

@Service
public class ReportService {
  private static final Logger log = LoggerFactory.getLogger(ReportService.class);

  public Report generate(Long marketId) {
    log.info("generate_report marketId={}", marketId);
    try {
      // 処理
    } catch (Exception ex) {
      log.error("generate_report_failed marketId={}", marketId, ex);
      throw ex;
    }
    return new Report();
  }
}

ミドルウェア / フィルター

@Component
public class RequestLoggingFilter extends OncePerRequestFilter {
  private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    long start = System.currentTimeMillis();
    try {
      filterChain.doFilter(request, response);
    } finally {
      long duration = System.currentTimeMillis() - start;
      log.info("req method={} uri={} status={} durationMs={}",
          request.getMethod(), request.getRequestURI(), response.getStatus(), duration);
    }
  }
}

ページネーションとソート

PageRequest page = PageRequest.of(pageNumber, pageSize, Sort.by("createdAt").descending());
Page<Market> results = marketService.list(page);

エラー耐性のある外部呼び出し

public <T> T withRetry(Supplier<T> supplier, int maxRetries) {
  int attempts = 0;
  while (true) {
    try {
      return supplier.get();
    } catch (Exception ex) {
      attempts++;
      if (attempts >= maxRetries) {
        throw ex;
      }
      try {
        Thread.sleep((long) Math.pow(2, attempts) * 100L);
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw ex;
      }
    }
  }
}

レート制限 (フィルター + Bucket4j)

セキュリティに関する注意: X-Forwarded-For ヘッダーはデフォルトでは信頼できません。クライアントが偽装できるためです。 フォワードヘッダーは以下の場合にのみ使用してください:

  1. アプリケーションが信頼できるリバースプロキシ (nginx、AWS ALB など) の背後にある場合
  2. ForwardedHeaderFilter を Bean として登録している場合
  3. アプリケーションプロパティで server.forward-headers-strategy=NATIVE または FRAMEWORK を設定している場合
  4. プロキシが X-Forwarded-For ヘッダーを追加 (append) ではなく上書き (overwrite) するように設定されている場合

ForwardedHeaderFilter が適切に設定されている場合、request.getRemoteAddr() は自動的にフォワードヘッダーから正しいクライアント IP を返します。この設定がない場合は、request.getRemoteAddr() を直接使用してください。これは接続元 IP を返し、これのみが信頼できる値です。

@Component
public class RateLimitFilter extends OncePerRequestFilter {
  private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();

  /*
   * セキュリティ: このフィルターはレート制限のために request.getRemoteAddr() を使用してクライアントを識別します。
   *
   * アプリケーションがリバースプロキシ (nginx、AWS ALB など) の背後にある場合、正確なクライアント IP を
   * 検出するために Spring でフォワードヘッダーを適切に処理するよう設定する必要があります:
   *
   * 1. application.properties/yaml で server.forward-headers-strategy=NATIVE (クラウドプラットフォーム向け)
   *    または FRAMEWORK を設定
   * 2. FRAMEWORK 戦略を使用する場合、ForwardedHeaderFilter を登録:
   *
   *    @Bean
   *    ForwardedHeaderFilter forwardedHeaderFilter() {
   *        return new ForwardedHeaderFilter();
   *    }
   *
   * 3. プロキシが X-Forwarded-For ヘッダーを追加 (append) ではなく上書き (overwrite) することを確認
   * 4. コンテナに応じて server.tomcat.remoteip.trusted-proxies または同等の設定を行う
   *
   * この設定がない場合、request.getRemoteAddr() はクライアント IP ではなくプロキシ IP を返します。
   * X-Forwarded-For を直接読み取らないでください。信頼できるプロキシ処理なしでは簡単に偽装できます。
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    // ForwardedHeaderFilter が設定されている場合は正しいクライアント IP を、
    // そうでない場合は直接接続 IP を返す getRemoteAddr() を使用。
    // 適切なプロキシ設定なしに X-Forwarded-For ヘッダーを直接信頼してはいけません。
    String clientIp = request.getRemoteAddr();

    Bucket bucket = buckets.computeIfAbsent(clientIp,
        k -> Bucket.builder()
            .addLimit(Bandwidth.classic(100, Refill.greedy(100, Duration.ofMinutes(1))))
            .build());

    if (bucket.tryConsume(1)) {
      filterChain.doFilter(request, response);
    } else {
      response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
    }
  }
}

バックグラウンドジョブ

Spring の @Scheduled を使用するか、キュー (例: Kafka、SQS、RabbitMQ) と統合します。ハンドラーは冪等かつ観測可能に保ちます。

観測可能性

  • 構造化ロギング (JSON): Logback エンコーダー経由
  • メトリクス: Micrometer + Prometheus/OTel
  • トレーシング: OpenTelemetry または Brave バックエンドを使用した Micrometer Tracing

本番環境のデフォルト設定

  • コンストラクタインジェクションを推奨、フィールドインジェクションは避ける
  • RFC 7807 エラーに対応するため spring.mvc.problemdetails.enabled=true を有効化 (Spring Boot 3+)
  • ワークロードに合わせて HikariCP のプールサイズを設定し、タイムアウトを設定
  • クエリには @Transactional(readOnly = true) を使用
  • @NonNull と Optional を適切に使用して null 安全性を確保

忘れないでください: コントローラーは薄く、サービスは集中的に、リポジトリはシンプルに、エラーは中央で処理しましょう。保守性とテスト容易性を最適化してください。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

関連スキル