Communitygithub.com

springboot-patterns

Patrones de arquitectura Spring Boot, diseño de API REST, servicios por capas, acceso a datos, caché, procesamiento asíncrono y registro. Útil para trabajo backend con Java Spring Boot. Actívalo al construir o revisar un backend Spring Boot: capa REST, servicios, acceso a datos, caché o procesamiento asíncrono.

¿Qué es springboot-patterns?

Este skill proporciona un conjunto completo de patrones y mejores prácticas para desarrollar servicios backend robustos y listos para producción con Spring Boot. Cubre desde la estructuración de API REST con Spring MVC/WebFlux, pasando por la implementación de las capas controlador, servicio y repositorio, hasta la configuración de acceso a datos con Spring Data JPA, validación con Bean Validation, manejo centralizado de excepciones y paginación. También incluye guías para caching con `@Cacheable`, procesamiento asíncrono con `@Async`, logging estructurado con SLF4J, filtros personalizados (como logging y rate limiting con Bucket4j), y resiliencia en llamadas externas con reintentos. Se enfatizan patrones de producción como inyección de constructores, uso de `@Transactional(readOnly = true)` para consultas, y observabilidad mediante logging JSON, métricas con Micrometer y tracing distribuido. Es ideal para cualquier desarrollador que trabaje en Spring Boot 3+ y necesite una referencia rápida de las prácticas recomendadas, con ejemplos de código Java claros y configuración de seguridad para proxies inversos. Compatible con Claude Code, Cursor, Codex y otras herramientas de IA que puedan leer SKILL.md.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/springboot-patterns

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Patrones de Desarrollo Spring Boot

Patrones de arquitectura y API de Spring Boot para servicios escalables de calidad de producción.

Cuándo Activar

  • Construyendo API REST con Spring MVC o WebFlux
  • Estructurando capas controlador → servicio → repositorio
  • Configurando Spring Data JPA, caché o procesamiento asíncrono
  • Agregando validación, manejo de excepciones o paginación
  • Configurando perfiles para entornos dev/staging/producción
  • Implementando patrones basados en eventos con Spring Events o Kafka

Estructura de API REST

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

Patrón de Repositorio (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);
}

Capa de Servicio con Transacciones

@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 y Validación

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

Manejo de Excepciones

@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) {
    // Registrar errores inesperados con trazas de pila
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
        .body(ApiError.of("Error interno del servidor"));
  }
}

Caché

Requiere @EnableCaching en una clase de configuración.

@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("Mercado no encontrado"));
  }

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

Procesamiento Asíncrono

Requiere @EnableAsync en una clase de configuración.

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

Registro (SLF4J)

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

  public Report generate(Long marketId) {
    log.info("generar_reporte marketId={}", marketId);
    try {
      // lógica
    } catch (Exception ex) {
      log.error("fallo_generar_reporte marketId={}", marketId, ex);
      throw ex;
    }
    return new Report();
  }
}

Middleware / Filtros

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

Paginación y Ordenación

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

Llamadas Externas Resilientes a Errores

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

Limitación de Tasa (Filtro + Bucket4j)

Nota de Seguridad: La cabecera X-Forwarded-For no es confiable de manera predeterminada porque los clientes pueden falsificarla. Usa cabeceras reenviadas solo cuando:

  1. Tu aplicación está detrás de un proxy inverso confiable (nginx, AWS ALB, etc.)
  2. Has registrado ForwardedHeaderFilter como un bean
  3. Has configurado server.forward-headers-strategy=NATIVE o FRAMEWORK en application properties
  4. Tu proxy está configurado para sobrescribir (no añadir) la cabecera X-Forwarded-For

Cuando ForwardedHeaderFilter está configurado correctamente, request.getRemoteAddr() devolverá automáticamente la IP correcta del cliente a partir de las cabeceras reenviadas. Sin esta configuración, usa request.getRemoteAddr() directamente—devuelve la IP de conexión inmediata, que es el único valor confiable.

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

  /*
   * SEGURIDAD: Este filtro utiliza request.getRemoteAddr() para identificar clientes para la limitación de tasa.
   *
   * Si tu aplicación está detrás de un proxy inverso (nginx, AWS ALB, etc.), DEBES configurar
   * Spring para manejar correctamente las cabeceras reenviadas para una detección precisa de la IP del cliente:
   *
   * 1. Configura server.forward-headers-strategy=NATIVE (para plataformas en la nube) o FRAMEWORK en
   *    application.properties/yaml
   * 2. Si usas la estrategia FRAMEWORK, registra ForwardedHeaderFilter:
   *
   *    @Bean
   *    ForwardedHeaderFilter forwardedHeaderFilter() {
   *        return new ForwardedHeaderFilter();
   *    }
   *
   * 3. Asegúrate de que tu proxy sobrescribe (no añade) la cabecera X-Forwarded-For para evitar suplantación
   * 4. Configura server.tomcat.remoteip.trusted-proxies o su equivalente para tu contenedor
   *
   * Sin esta configuración, request.getRemoteAddr() devuelve la IP del proxy, no la IP del cliente.
   * NO leas X-Forwarded-For directamente—es trivialmente falsificable sin manejo de proxy confiable.
   */
  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {
    // Usa getRemoteAddr() que devuelve la IP correcta del cliente cuando ForwardedHeaderFilter
    // está configurado, o la IP de conexión directa en caso contrario. Nunca confíes en las cabeceras
    // X-Forwarded-For directamente sin una configuración de proxy adecuada.
    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());
    }
  }
}

Trabajos en Segundo Plano

Usa @Scheduled de Spring o integra con colas (ej., Kafka, SQS, RabbitMQ). Mantén los manejadores idempotentes y observables.

Observabilidad

  • Registro estructurado (JSON) mediante codificador Logback
  • Métricas: Micrometer + Prometheus/OTel
  • Trazado: Micrometer Tracing con backend OpenTelemetry o Brave

Valores Predeterminados de Producción

  • Prefiere inyección por constructor, evita inyección por campo
  • Activa spring.mvc.problemdetails.enabled=true para errores RFC 7807 (Spring Boot 3+)
  • Configura tamaños de pool HikariCP según la carga de trabajo, establece tiempos de espera
  • Usa @Transactional(readOnly = true) para consultas
  • Aplica seguridad de nulos mediante @NonNull y Optional cuando sea apropiado

Recuerda: Mantén los controladores ligeros, los servicios enfocados, los repositorios simples y los errores manejados de forma centralizada. Optimiza para mantenibilidad y testabilidad.

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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills relacionados