Video in progress

Staff 🌱 Spring

Several teams are working in one large Spring codebase. How do you keep architectural boundaries from being broken?

I keep the rules in automated tests, not in a document: ArchUnit or Spring Modulith checks package and module dependencies in CI. On top of that I add code ownership (CODEOWNERS), a clear contract for module APIs, and an open "exception" process for breaking a boundary.

📖 Answer

ArchUnit rules:

@AnalyzeClasses(packages = "uz.shop")
class ArchitectureTest {

    @ArchTest
    static final ArchRule layers = layeredArchitecture().consideringOnlyDependenciesInLayers()
        .layer("Web").definedBy("..web..")
        .layer("Service").definedBy("..service..")
        .layer("Persistence").definedBy("..repository..")
        .whereLayer("Web").mayNotBeAccessedByAnyLayer()
        .whereLayer("Persistence").mayOnlyBeAccessedByLayers("Service");

    @ArchTest
    static final ArchRule noCycles = slices().matching("uz.shop.(*)..").should().beFreeOfCycles();

    @ArchTest
    static final ArchRule internalsHidden = noClasses().that().resideOutsideOfPackage("..billing..")
        .should().dependOnClassesThat().resideInAPackage("..billing.internal..");
}

In an old project, if you turn on every rule at once, you get hundreds of violations. ArchUnit's FreezingArchRule "freezes" the existing ones and forbids only new ones, and you reduce the old ones gradually.

Supporting tools:

  • CODEOWNERS: a change in a module's code must be reviewed by the team that owns it;
  • the module API: other teams use only the api package, and changing it means changing the contract;
  • Gradle/Maven build modules: the hardest boundary, since the compiler itself won't allow a violation, but managing the modules also costs effort;
  • ADRs: write down why the boundaries are where they are.

If you work out the rules together with the team, they're seen not as "bureaucracy" but as something that protects everyone.