Architecture is the set of decisions that are expensive to change later: how code is divided, which parts may depend on which, and where cross-cutting concerns live. To create a Java project architecture, first define the system's bounded contexts and module boundaries, then choose a layered or hexagonal structure inside each module, enforce the dependency rules with the build tool, and only then write code. Spring Boot with a multi-module Maven or Gradle build is the most common starting point in 2026, but the same principles apply to plain Java or Jakarta EE. The key condition: decide package and module boundaries before the codebase grows, because retrofitting them costs far more than designing them up front.
Start With Boundaries, Not Folders
The most common failure in Java projects is starting from directories — "let's make a controller package and a service package" — rather than from the business capabilities the system actually has. Folders follow boundaries; they don't create them.
A workable sequence for the first day of a project:
1: List the system's business capabilities as verbs ("place order," "issue refund," "send notification"). Group closely related ones into candidate bounded contexts — order management, billing, notifications. 2: For each context, ask what data it owns and what it must ask other contexts for. If two contexts constantly need each other's tables, they may be one context, or the boundary is wrong. 3: Decide the deployment model: a modular monolith (one deployable, many internal modules) or separate services. For most new projects, a modular monolith is the right first choice; service boundaries can be extracted later precisely because the module boundaries already exist. 4: Write the boundary names down. One sentence per module describing its responsibility and what it must never do is enough — this document is the architecture, not the diagram.
The check for success is simple: for any new feature request, you should be able to name the one module that owns it and list at most one or two other modules it must call. If every feature touches every module, the boundaries are decorative.
Choose a Structural Style and Apply It Consistently
Inside each module, pick one dependency style and stay with it. Two dominate Java practice.
Layered (controller → service → repository) is the default because frameworks and tutorials assume it. Its weakness is that the domain model tends to leak: services hold business rules, repositories are called directly from controllers in a hurry, and the "domain" is a set of anemic data classes.
Hexagonal (ports and adapters) puts the domain model at the center with no framework imports, defines incoming ports (use-case interfaces) and outgoing ports (repository, messaging, clock interfaces), and implements adapters — web controllers, JPA repositories, message listeners — at the edges. Dependencies point inward. This costs a bit more boilerplate per feature but keeps business rules testable without a database or Spring context.
A pragmatic hybrid many teams use: hexagon inside complex or long-lived modules, plain layers inside small CRUD modules. Mixing styles across modules is fine; mixing them within a module is where confusion starts.
The rule that matters in either style: domain code never imports web, persistence, or messaging frameworks. If a @RestController annotation appears in a class that also contains pricing rules, the structure has already failed.
Lay Out Packages So the Compiler Can See the Architecture
Package-by-feature beats package-by-layer at scale. For a storefront with a hexagonal order module, a structure like this works:
Notice that the web adapter and persistence adapter live inside the order module, not in a global controllers or repositories package. That placement is what makes module boundaries enforceable: everything under order is the order module's business, and nothing outside it may touch order.domain or order.adapter.
The shared package is the most dangerous one in any Java codebase. It starts with a Money value object and ends up importing half the application. Keep it to primitives and pure utilities, and allow it to depend on nothing.
Sequence the Build From Prerequisites to Enforcement
The following steps give a workable order for a new Spring Boot project. Prerequisites: JDK 21 or newer (LTS releases through 2026 include 21 and 25), a build tool (Maven 3.9+ or Gradle 8.x+), and a single sentence per module describing its responsibility.
1: Create the root build. A Maven multi-module POM with pom, or a Gradle settings file listing subprojects. Put dependency versions in one place — Maven's dependencyManagement or Gradle's version catalog (gradle/libs.versions.toml) — so modules can't drift apart. 2: Create one module per bounded context as subdirectories with their own build files, plus a thin bootstrap (or app) module whose only job is the Spring Boot main class, configuration files, and assembling the runnable jar. Keeping bootstrap separate means the domain modules never need to know how the application starts. 3: Create the package skeleton inside each module using the domain/application/adapter layout above. Empty packages for now; the point is that the first class written lands in the right place. 4: Declare inter-module dependencies explicitly. If order needs billing's pricing, depend on a narrow published interface rather than the whole module where the build tool allows it; in Maven, at minimum keep the dependency graph acyclic — billing must not depend back on order. 5: Set up the database boundary. Give each module its own schema (or prefixed tables) and its own migration directory — Flyway or Liquibase — so it's visible when one module starts querying another's tables. Cross-module reads go through the owning module's interface, not raw SQL. 6: Add architecture tests before writing features. ArchUnit runs as a normal JUnit test and can assert "domain classes do not depend on org.springframework," "adapters may depend on domain, not the reverse," and "no cycles between modules." Write three or four such rules on day one; they are cheap and catch the first violation while it's still one line to fix. 7: Build one vertical slice end to end — a single use case through controller, application service, domain rule, and repository — and get it passing. This validates the wiring and gives the team a template to copy. 8: Add the cross-cutting layer once, centrally: logging configuration, error-handling advice, security, and observability. In Spring Boot, an @RestControllerAdvice and a shared error type in shared keep error responses consistent; do not let each module roll its own.
Success check: run the build and the ArchUnit suite, then add a deliberately wrong import (a Spring annotation in a domain class) and confirm the test fails. If it doesn't, the enforcement isn't wired to the build lifecycle — fix that before continuing. Stop and involve a senior architect or platform team if the module dependency graph already has cycles you can't break by moving a class or two; cycles at that stage usually signal that the boundary analysis in step one was wrong.
Make Dependency Direction a Build-Time Rule
Documentation about layering decays; build rules don't. Three mechanisms, in increasing strength:
Package conventions plus ArchUnit (available for years, stable API): enough for most teams. Rules live next to the tests, and a failing rule blocks the merge. Java modules (JPMS) with module-info.java: real compile-time encapsulation — a module can export its port interfaces and hide its domain classes. Worth it for libraries and larger monoliths; it adds friction with some frameworks and annotation processors, so test the toolchain early. Separate builds/repositories per module: the strongest boundary, appropriate only when modules deploy or version independently, because cross-repo changes become coordination work.
A common middle ground in 2026: multi-module build with ArchUnit enforcing layers inside modules, and Maven/Gradle enforcing that module A can't depend on module B's adapter packages (by convention: adapters are internal by naming and checked by rule, since build tools manage modules, not packages).
Decide Where Framework and Persistence Code Lives
Two decisions shape daily life more than any diagram.
First, domain model versus persistence model. You can map domain objects directly with JPA, or keep separate persistence entities and translate. Direct mapping is less code but couples the domain to JPA's constraints (no-arg constructors, lazy proxies, identity semantics). Separate entities cost mappers but let the domain stay pure and let the schema evolve independently. For modules with rich rules, separate; for thin CRUD, direct mapping is defensible.
Second, transaction boundaries. Put them at the application-service (use case) level, not in controllers or repositories. A use case that spans two modules should coordinate through their ports and accept that cross-module consistency is eventual where data is split — in a monolith you can still use one database, but keep the rule that only the owning module writes its tables. The practical check: search for @Transactional in controllers and repositories; ideally you find none.
Design the Cross-Cutting Concerns Before They Multiply
Logging, error handling, security, validation, and configuration are the concerns that get copy-pasted if not centralized on day one.
Errors: one error hierarchy in shared, one exception-handling advice mapping domain exceptions to HTTP responses. Avoid catching Exception in controllers. Validation: Bean Validation annotations on incoming DTOs at the adapter edge; domain invariants enforced in constructors and factory methods in the domain, because a service can be called from a message listener as well as a controller. Security: keep authorization at the adapter or application boundary. Domain code should receive an already-authorized caller identity, not query a security context. Configuration: one place for properties per environment; typed configuration classes rather than scattered @Value lookups, so missing keys fail at startup rather than at 2 a.m. Observability: request correlation IDs and structured logs configured once in bootstrap. Modules log their own events; they don't configure appenders.
Each of these is a small decision now and an expensive refactor after fifty classes copy the wrong pattern.
Get Testing and the Build Pipeline Right Early
Architecture without a test strategy is a claim nobody verifies. A practical pyramid for this structure:
Domain unit tests — fast, no framework, the bulk of tests for complex modules. Use-case tests with in-memory implementations of the ports (a fake repository, a fixed clock). Adapter tests — @WebMvcTest-style slices for controllers, Testcontainers for real database behavior in repositories. These run slower; keep them focused on mapping and queries. One or two end-to-end smoke tests per deployable.
Wire the same checks into continuous integration that you run locally: compile, unit tests, architecture tests, and the integration slice. If the build is slow because integration tests dominate, split into a fast stage (unit plus architecture) that gates merges and a slower stage that gates releases.
Version and Region Notes That Affect the Blueprint
JDK 25, an LTS release, is available as of late 2026, and Spring Boot 3.x requires Java 17 as a baseline, so a project starting on JDK 21 or 25 has headroom. Spring Boot 4.x-era releases (2026) keep Jakarta EE namespaces — jakarta.persistence, jakarta.validation — so imports from older javax.* tutorials will not compile. Build-tool plugin versions and framework minor versions change frequently; check the current stable versions at project start rather than copying an old pom.xml, since version availability is exactly the kind of value that shifts month to month. None of the structural decisions above depend on those versions.
Worked Estimate: What Separating Persistence Entities Costs
An illustrative sizing, not measured data: suppose an order module has five aggregates with roughly six fields each. Direct JPA mapping might take about 30 field declarations plus annotations. Separate persistence entities plus mappers add roughly the same fields again in entity classes, one mapper class per aggregate, and mapping code in the repository adapter — call it two to three times the persistence code for that module.
The return arrives later. A schema migration that renames columns touches entities and mappers only, and domain tests that previously needed a database no longer do. For a module with two or three aggregates that stay thin, the extra code rarely pays back; for one with pricing rules and state machines, it usually does within the first few non-trivial changes. Apply the split selectively at module level rather than as a project-wide mandate.
Failure Cases Worth Recognizing Early
The shared module swallows everything. Symptom: shared imports from three modules. Cause: convenience-driven refactoring. Fix: anything used by exactly one module moves back into that module. The web layer becomes the application layer. Symptom: controllers orchestrate multiple services and map between five DTOs. Cause: no use-case interfaces. Fix: introduce application services per use case and thin the controllers. Module cycles. Symptom: build fails after adding a dependency, or ArchUnit reports a cycle. Cause: a boundary that splits one capability in two. Fix: merge the modules or extract the shared concept into its own module; don't "solve" it by depending on the whole module. Architecture tests that assert nothing. Symptom: rules reference packages that were renamed and silently match nothing. Fix: assert on a small non-empty package and verify a deliberately bad import fails, as described above. One giant integration-test suite. Symptom: builds take 20 minutes and people merge without running them. Cause: no test pyramid. Fix: move rule coverage down to domain unit tests.
FAQ
Do I need microservices to have good architecture? No. The module boundaries described here are the architecture; deployment is a separate axis. A modular monolith with enforced boundaries extracts into services far more cleanly than an unstructured monolith ever could.
Should I use Maven or Gradle? Either enforces module dependency direction. Maven's multi-module POM is more rigid and therefore slightly easier to keep consistent; Gradle's version catalog and convention plugins reduce duplication in larger builds. Pick based on your team's existing tooling — this choice is genuinely reversible, unlike the boundaries.
Where do DTOs belong? In the adapter that uses them — web DTOs under the web adapter, message DTOs under the messaging adapter. Sharing one DTO type across web and messaging couples two edges that change for different reasons. Map between DTO and domain at the adapter boundary.
How many modules is too many? If a module contains one class or exists only to hold a utility, it's probably not a boundary. Aim for modules that a person could own and describe in one sentence; teams of five to ten typically land somewhere between four and a dozen.