Communitygithub.com

Spring Boot 驗證循環

適用於 Spring Boot 專案的驗證循環:建構、靜態分析、測試含覆蓋率、安全掃描,以及在發布或 PR 前的差異審查。

Spring Boot 驗證循環 是什麼?

這個技能定義了一套完整的 Spring Boot 專案驗證循環,涵蓋建構、靜態分析、測試與覆蓋率、安全掃描、程式碼格式檢查和差異審查。開發者在提交 PR、重大重構或部署前,可以透過一系列 CLI 命令(Maven 或 Gradle)自動化執行這些檢查,確保程式碼品質。技能支援 Testcontainers 進行真實資料庫整合測試、MockMvc 進行 API 層測試,以及 OWASP 依賴性檢查和秘密掃描等安全措施。最終會產出標準化的報告模板,幫助團隊快速判斷專案是否準備就緒。此技能特別適合需要嚴格把關程式碼品質與安全性的 Spring Boot 開發環境。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/springboot-verification

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Spring Boot 驗證循環 是做什麼的?

在 PR 前、重大變更後及部署前執行。

何時啟用

  • 在為 Spring Boot 服務開啟拉取請求之前
  • 在重大重構或依賴升級之後
  • 預先部署驗證,適用於 staging 或 production 環境
  • 執行完整的建構 → lint → 測試 → 安全掃描流程
  • 驗證測試覆蓋率是否達到門檻

階段 1:建構

mvn -T 4 clean verify -DskipTests
# 或者
./gradlew clean assemble -x test

如果建構失敗,請停止並修復。

階段 2:靜態分析

Maven(常用外掛):

mvn -T 4 spotbugs:check pmd:check checkstyle:check

Gradle(若已設定):

./gradlew checkstyleMain pmdMain spotbugsMain

階段 3:測試 + 覆蓋率

mvn -T 4 test
mvn jacoco:report   # 驗證 80% 以上的覆蓋率
# 或者
./gradlew test jacocoTestReport

報告:

  • 總測試數、通過/失敗
  • 覆蓋率 %(程式行/分支)

單元測試

使用模擬的依賴隔離測試服務邏輯:

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

  @Mock private UserRepository userRepository;
  @InjectMocks private UserService userService;

  @Test
  void createUser_validInput_returnsUser() {
    var dto = new CreateUserDto("Alice", "[email protected]");
    var expected = new User(1L, "Alice", "[email protected]");
    when(userRepository.save(any(User.class))).thenReturn(expected);

    var result = userService.create(dto);

    assertThat(result.name()).isEqualTo("Alice");
    verify(userRepository).save(any(User.class));
  }

  @Test
  void createUser_duplicateEmail_throwsException() {
    var dto = new CreateUserDto("Alice", "[email protected]");
    when(userRepository.existsByEmail(dto.email())).thenReturn(true);

    assertThatThrownBy(() -> userService.create(dto))
        .isInstanceOf(DuplicateEmailException.class);
  }
}

使用 Testcontainers 的整合測試

針對真實資料庫而不是 H2 進行測試:

@SpringBootTest
@Testcontainers
class UserRepositoryIntegrationTest {

  @Container
  static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
      .withDatabaseName("testdb");

  @DynamicPropertySource
  static void configureProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
  }

  @Autowired private UserRepository userRepository;

  @Test
  void findByEmail_existingUser_returnsUser() {
    userRepository.save(new User("Alice", "[email protected]"));

    var found = userRepository.findByEmail("[email protected]");

    assertThat(found).isPresent();
    assertThat(found.get().getName()).isEqualTo("Alice");
  }
}

使用 MockMvc 的 API 測試

使用完整的 Spring context 測試 Controller 層:

@WebMvcTest(UserController.class)
class UserControllerTest {

  @Autowired private MockMvc mockMvc;
  @MockBean private UserService userService;

  @Test
  void createUser_validInput_returns201() throws Exception {
    var user = new UserDto(1L, "Alice", "[email protected]");
    when(userService.create(any())).thenReturn(user);

    mockMvc.perform(post("/api/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""
                {"name": "Alice", "email": "[email protected]"}
                """))
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.name").value("Alice"));
  }

  @Test
  void createUser_invalidEmail_returns400() throws Exception {
    mockMvc.perform(post("/api/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""
                {"name": "Alice", "email": "not-an-email"}
                """))
        .andExpect(status().isBadRequest());
  }
}

階段 4:安全掃描

# 依賴 CVE
mvn org.owasp:dependency-check-maven:check
# 或者
./gradlew dependencyCheckAnalyze

# 原始碼中的秘密
find src/ -name "*.java" -o -name "*.yml" -o -name "*.properties" | xargs grep -rn "password\s*=\s*\""
find src/ -name "*.java" -o -name "*.yml" | xargs grep -rn "sk-\|api_key\|secret"

# 秘密(git 歷史)
git secrets --scan  # 若已設定

常見安全發現

# 檢查 System.out.println(請改用 logger)
find src/main/ -name "*.java" | xargs grep -rn "System\.out\.print"

# 檢查回應中原始例外訊息
find src/main/ -name "*.java" | xargs grep -rn "e\.getMessage()"

# 檢查萬用字元 CORS
find src/main/ -name "*.java" | xargs grep -rn "allowedOrigins.*\*"

階段 5:程式碼格式檢查(選擇性門檻)

mvn spotless:apply   # 如果使用 Spotless 外掛
./gradlew spotlessApply

階段 6:差異審查

git diff --stat
git diff

檢查清單:

  • 沒有遺留的除錯日誌(System.out、未加防護的 log.debug)
  • 有意義的錯誤和 HTTP 狀態碼
  • 交易和驗證在需要的地方存在
  • 配置變更有文件記錄

輸出範本

驗證報告
========
建構:     [通過/失敗]
靜態:     [通過/失敗] (spotbugs/pmd/checkstyle)
測試:     [通過/失敗] (X/Y 通過,Z% 覆蓋率)
安全:     [通過/失敗] (CVE 發現:N)
差異:     [X 個檔案變更]

總體:     [準備就緒 / 尚未就緒]

待修復問題:
1. ...
2. ...

持續模式

  • 在重大變更時或長時間工作階段中每 30–60 分鐘重新執行各階段
  • 保持短循環:mvn -T 4 test + spotbugs 以獲得快速回饋

請記住:快速回饋勝過事後驚喜。保持嚴格的門檻——將警告視為生產系統中的缺陷。

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.

相關技能