Enforcing Java Layering Rules with ArchUnit and Claude Code
A Juejin article reports a hands-on test in which ArchUnit architecture tests plus a Claude Code Stop hook blocked a layering violation before the coding agent finished. In the author's minimal Java project, a CLAUDE.md instruction merely triggered a warning, while the test-and-hook setup returned a failed test to Claude for correction. The author also reproduced a case where Maven Surefire 3.5.3 reported zero ArchUnit tests despite a build success, plus a hook error-handling issue that silently disabled enforcement.
The report offers a concrete verification pattern for teams using coding agents: enforce architectural boundaries with executable tests and a completion hook rather than relying only on written project instructions.
导读:Hacker News 这两天有篇 352 分的文章叫《AI usage generates a fragile codebase》,说用 AI 写代码,项目会越写越脆。知乎上"用 AI 写的代码,最终会不会让整个项目成为屎山"也有 92 万浏览。我更关心能落地的一件事:项目里那些"Controller 不能直接调 Mapper"之类的规矩,怎么让 AI 真的守住。本文在一个最小的 Java 项目里实测:只写在 CLAUDE.md 里拦不住;写成 ArchUnit 测试,再配一个 Claude Code 的 Stop hook,Claude 交活前自动跑测试、不过就打回去改,实测能拦住。中间踩到两个坑,一个在 Maven surefire 3.5.3,一个在 Claude Code 的 hook 报错判断,都会让门禁悄悄失效。
版本说明:Claude Code 2.1.299,模型 Sonnet;JDK 17.0.12,Maven 3.6.3,ArchUnit 1.5.1,JUnit 5.12.2,maven-surefire-plugin 3.5.3 / 3.5.4 等多个版本对比。演示项目是 scratchpad 里临时建的 5 个类,不是业务项目。
一、先说清楚:要解决的是什么问题
先讲白话。一个 Spring Boot 项目一般分三层:Controller 接请求,Service 写业务逻辑,Mapper 查数据库。团队约定 Controller 只能调 Service、不能绕过 Service 直接查库,是因为事务、权限校验、缓存都放在 Service 层,绕过去就全漏了。
#Claude Code Stop hook#ArchUnit#Apache Maven Surefire 3.5.3#Claude Sonnet#JUnit 5#CLAUDE.md