Communitygithub.com

springboot-patterns

Spring Boot-Architekturmuster, REST-API-Design, geschichtete Dienste, Datenzugriff, Caching, asynchrone Verarbeitung und Logging. Für Java Spring-Backend-Arbeiten. Verwenden Sie dies beim Erstellen oder Überprüfen eines Spring-Boot-Backends – REST-Schicht, Dienste, Datenzugriff, Caching oder asynchrone Arbeiten.

Was ist springboot-patterns?

Dieses Skill, „springboot-patterns“, dient als umfassender Leitfaden für die Entwicklung skalierbarer, produktionsreifer Spring Boot-Backends, die auf der Java-Plattform aufbauen. Es behandelt die gesamte Architektur von der REST-API-Erstellung mit Spring MVC oder WebFlux über die Strukturierung geschichteter Controller-Service-Repository-Schichten bis hin zur Konfiguration von Spring Data JPA, Caching und asynchroner Verarbeitung. Der Skill bietet konkrete Codebeispiele für robuste DTOs mit Validierung, zentrale Ausnahmebehandlung und sicheres Caching mit `@Cacheable`. Er ist plattformunabhängig und kann in jeder Spring Boot-Umgebung eingesetzt werden, einschließlich Cursor, Claude Code, Codex und anderen KI-Assistenten. Darüber hinaus werden Sicherheitsaspekte wie korrektes IP-Handling hinter Reverse-Proxys behandelt und bewährte Methoden für die Produktion wie strukturierte Protokollierung, Metriken mit Micrometer und Datenbank-Pooling vermittelt.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Spring Boot Entwicklungsmuster

Spring Boot Architektur- und API-Muster für skalierbare, produktionsreife Dienste.

Wann aktivieren

  • Erstellen von REST-APIs mit Spring MVC oder WebFlux
  • Strukturieren der Schichten Controller → Service → Repository
  • Konfigurieren von Spring Data JPA, Caching oder asynchroner Verarbeitung
  • Hinzufügen von Validierung, Ausnahmebehandlung oder Paginierung
  • Einrichten von Profilen für Entwicklungs-/Staging-/Produktionsumgebungen
  • Implementieren ereignisgesteuerter Muster mit Spring Events oder Kafka

REST-API-Struktur

@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));
  }
}

Repository-Muster (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);
}

Dienstschicht mit Transaktionen

@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);
  }
}

DTOs und Validierung

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());
  }
}

Ausnahmebehandlung

@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) {
    // Log unerwartete Fehler mit Stack-Traces
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(ApiError.of("Interner Serverfehler"));
  }
}

Caching

Erfordert @EnableCaching auf einer Konfigurationsklasse.

@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("Markt nicht gefunden"));
  }

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

Asynchrone Verarbeitung

Erfordert @EnableAsync auf einer Konfigurationsklasse.

@Service
public class NotificationService {
  @Async
  public CompletableFuture<Void> sendAsync(Notification notification) {
    // E-Mail/SMS senden
    return CompletableFuture.completedFuture(null);
  }
}

Logging (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 {
      // Logik
    } catch (Exception ex) {
      log.error("generate_report_failed marketId={}", marketId, ex);
      throw ex;
    }
    return new Report();
  }
}

Middleware / Filter

@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);
    }
  }
}

Paginierung und Sortierung

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

Fehlertolerante externe Aufrufe

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;
      }
    }
  }
}

Rate Limiting (Filter + Bucket4j)

Sicherheitshinweis: Der X-Forwarded-For-Header ist standardmäßig nicht vertrauenswürdig, da Clients ihn fälschen können. Verwenden Sie Weiterleitungs-Header nur, wenn:

  1. Ihre App hinter einem vertrauenswürdigen Reverse-Proxy (nginx, AWS ALB usw.) läuft
  2. Sie ForwardedHeaderFilter als Bean registriert haben
  3. Sie server.forward-headers-strategy=NATIVE oder FRAMEWORK in den Anwendungseigenschaften konfiguriert haben
  4. Ihr Proxy so konfiguriert ist, dass er den X-Forwarded-For-Header überschreibt (nicht anhängt)

Wenn ForwardedHeaderFilter korrekt konfiguriert ist, gibt request.getRemoteAddr() automatisch die korrekte Client-IP aus den Weiterleitungs-Headern zurück. Ohne diese Konfiguration verwenden Sie request.getRemoteAddr() direkt – es gibt die IP der direkten Verbindung zurück, die der einzig vertrauenswürdige Wert ist.

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

  /*
   * SICHERHEIT: Dieser Filter verwendet request.getRemoteAddr() zur Identifizierung von Clients für Rate Limiting.
   *
   * Wenn Ihre Anwendung hinter einem Reverse-Proxy (nginx, AWS ALB usw.) läuft, MÜSSEN Sie Spring
   * für die korrekte Verarbeitung von Weiterleitungs-Headern konfigurieren, um die Client-IP korrekt zu erkennen:
   *
   * 1. Setzen Sie server.forward-headers-strategy=NATIVE (für Cloud-Plattformen) oder FRAMEWORK in
   *    application.properties/yaml
   * 2. Wenn Sie die FRAMEWORK-Strategie verwenden, registrieren Sie ForwardedHeaderFilter:
   *
   *    @Bean
   *    ForwardedHeaderFilter forwardedHeaderFilter() {
   *        return new ForwardedHeaderFilter();
   *    }
   *
   * 3. Stellen Sie sicher, dass Ihr Proxy den X-Forwarded-For-Header überschreibt (nicht anhängt), um Fälschungen zu verhindern
   * 4. Konfigurieren Sie server.tomcat.remoteip.trusted-proxies oder das Äquivalent für Ihren Container
   *
   * Ohne diese Konfiguration gibt request.getRemoteAddr() die Proxy-IP zurück, nicht die Client-IP.
   * Lesen Sie X-Forwarded-For NIEMALS direkt aus – ohne vertrauenswürdige Proxy-Konfiguration ist es trivial fälschbar.
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    // Verwenden Sie getRemoteAddr(), das die korrekte Client-IP zurückgibt, wenn ForwardedHeaderFilter
    // konfiguriert ist, andernfalls die IP der direkten Verbindung. Vertrauen Sie NIEMALS direkt auf
    // X-Forwarded-For-Header ohne korrekte Proxy-Konfiguration.
    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());
    }
  }
}

Hintergrundjobs

Verwenden Sie Springs @Scheduled oder integrieren Sie Warteschlangen (z. B. Kafka, SQS, RabbitMQ). Halten Sie Handler idempotent und beobachtbar.

Beobachtbarkeit

  • Strukturiertes Logging (JSON) über Logback-Encoder
  • Metriken: Micrometer + Prometheus/OTel
  • Tracing: Micrometer Tracing mit OpenTelemetry oder Brave-Backend

Produktionsstandards

  • Bevorzugen Sie Konstruktor-Injection, vermeiden Sie Field-Injection
  • Aktivieren Sie spring.mvc.problemdetails.enabled=true für RFC 7807 Fehler (Spring Boot 3+)
  • Konfigurieren Sie HikariCP-Poolgrößen für die Arbeitslast, setzen Sie Timeouts
  • Verwenden Sie @Transactional(readOnly = true) für Abfragen
  • Erzwingen Sie Nullsicherheit über @NonNull und Optional wo angemessen

Denken Sie daran: Halten Sie Controller schlank, Dienste fokussiert, Repositories einfach und Fehler zentral behandelt. Optimieren Sie für Wartbarkeit und Testbarkeit.

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.

Verwandte Skills