Skip to content
javahacks.dev
Architecture

Package by Feature Java Layout Instead of Package by Layer

Organise Java packages by feature instead of by layer: a layout for Spring Boot, package private visibility, shared code rules and a path to modules.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, Spring Boot, Gradle, Apache Maven and JUnit5 logos.

The first thing a new developer sees in a project is the package list. It says what the system is, or only what framework it uses.

By layer

Text
com.example.shop
  controller/   OrderController, CustomerController, InvoiceController
  service/      OrderService, CustomerService, InvoiceService
  repository/   OrderRepository, CustomerRepository, InvoiceRepository
  model/        Order, Customer, Invoice

This shape is the tutorial default. It says "Spring MVC application" and tells you nothing about orders or invoices. Adding a field to an order touches four packages. Every class must be public so other packages can reach it, so nothing stops InvoiceController from calling OrderRepository.

By feature

Text
com.example.shop
  orders/      OrderController, OrderService, OrderRepository, Order, OrderStatus
  billing/     InvoiceController, InvoiceService, InvoiceRepository, Invoice
  customers/   CustomerController, CustomerService, ...
  shared/      Money, Clock configuration, error handling

The package list now reads as the business. A change to orders stays in orders. Deleting a feature is deleting a folder. The structure matches how teams divide work, and it reflects a bounded context at a small scale, the direction in service boundaries.

Use visibility

With classes in the same package, most can be package-private:

java
package com.example.shop.orders;

public class OrderFacade {                       // the feature's public face
    private final OrderService service;
    OrderFacade(OrderService service) { this.service = service; }
    public OrderView place(PlaceOrder command) { return service.place(command); }
}

class OrderService { ... }                       // package-private
interface OrderRepository extends JpaRepository<Order, Long> { }   // package-private

Other packages can use OrderFacade and nothing else. The compiler enforces the boundary. Spring can inject package-private classes, and controllers in the same package can use them. Spring Data repository interfaces may be package-private as well.

Rules that keep it working

  1. One public entry point per feature. A facade, an interface, or a few types that form the contract.
  2. Features depend on each other's public API only, never on internals. Check it with a test, see enforcing module boundaries.
  3. Avoid cycles between features. If orders and billing need each other, extract a third piece, or communicate through events.
  4. **Keep shared small.** If it grows to half the code, the features are not independent.
  5. Entities stay inside their feature. Pass IDs or view records across the boundary, not entities, which avoids cross-feature joins in the model.

Layers inside a feature

Feature packages can have sub-packages (orders.web, orders.domain, orders.persistence) when a feature is large. The top level stays the feature, the inside can follow a layering, as in hexagonal architecture.

Spring Boot specifics

The main class sits in the root package, so scanning finds all features, as explained in project structure. Spring Modulith goes a step further: each direct sub-package of the application package is a module, and its tests verify that modules use only each other's public API.

Moving an existing project

Do not reorganize everything in one commit. Pick the feature you change most, move its classes into a new package with IDE refactoring, make what you can package-private, and add a test for the boundary. Repeat as features are touched. The rename is cheap, the dependencies it reveals are the valuable part.

Make the layout enforceable with a test

A package layout is a convention until a test enforces it, and then it is a design. ArchUnit reads compiled classes and checks rules about packages and dependencies. This example has three feature packages: shop.order with a package-private repository, shop.billing that calls the public OrderService, and shop.web. The rules run on ArchUnit 1.4.1.

src/test/java/ArchTest.javajava
JavaClasses classes = new ClassFileImporter().importPath("target/classes");

@Test void orderInternalsStayInsideOrder() {
    noClasses().that().resideOutsideOfPackage("shop.order..")
            .should().dependOnClassesThat().haveSimpleName("OrderRepository")
            .check(classes);
}

@Test void billingMustNotDependOnWeb() {
    noClasses().that().resideInAPackage("shop.billing..")
            .should().dependOnClassesThat().resideInAPackage("shop.web..")
            .check(classes);
}

@Test void featuresHaveNoCycles() {
    slices().matching("shop.(*)..").should().beFreeOfCycles().check(classes);
}

All three passed. A fourth rule, "billing must not depend on order", was added to see a violation, and it failed with a message that names the call site:

Text
Rule 'no classes that reside in a package 'shop.billing..' should depend on classes that reside in a package 'shop.order..'' was violated (3 times):
Method <shop.billing.InvoiceService.invoiceFor(long)> calls method <shop.order.OrderService.get(long)> in (InvoiceService.java:3)

That is the whole value of the approach: the intended structure is a failing test the moment someone breaks it, and the message says which method and which line. The first rule relies on Java visibility. Because OrderRepository is package-private, the compiler already forbids use from outside shop.order, and the ArchUnit rule is a second guard in case someone makes it public. The slices rule finds cycles between features, which is the earliest sign that two features should be merged or that a shared concept needs its own package.

What a feature package contains

Put everything that changes together in one package: the controller, the service, the repository, the entity, the DTOs and the mapper. A developer adding a field to an order edits files in one directory, and the package-private default hides the parts other features have no business using. Expose a small public surface, usually one service interface or class and the types in its signatures.

Text
shop/
  order/
    Order.java               public (the type other features use)
    OrderService.java        public
    OrderController.java     package-private
    OrderRepository.java     package-private
    OrderMapper.java         package-private
  billing/
    InvoiceService.java      public
    InvoiceRepository.java   package-private

By layer, the same system has a controller package with every controller, a service package with every service, and a repository package with every repository. Each class there must be public so that the others can see it, which means nothing is hidden and every class is available to every other. The layout tells a reader how the code is built, not what it does.

Features talk through public APIs and events

Two features that must cooperate should do it through the public service of one, or through events, never through each other's repositories. When billing needs order data, it calls OrderService.get(id) and receives a small value type, not the entity. When something happens in one feature that others care about, publish an event and let them subscribe, as the modular monolith post does with Spring Modulith, which enforces these rules and also generates documentation of the dependencies.

java
public record OrderPlaced(long orderId, BigDecimal total) { }

@Service
class OrderService {
    private final ApplicationEventPublisher events;

    public Order place(NewOrder cmd) {
        Order order = repo.save(Order.from(cmd));
        events.publishEvent(new OrderPlaced(order.id(), order.total()));
        return order;
    }
}

Billing listens for OrderPlaced without order knowing it exists. The arrow of dependency points from billing to the event type in order, and removing the billing feature requires no change in order.

Move an existing project one feature at a time

A layered project does not need a big-bang reorganisation. Pick the feature that changes most often, create its package, and move its classes with the IDE's refactoring, which updates imports. Make what can be package-private package-private, and fix the compile errors that show you the hidden coupling. Add the ArchUnit rules for that feature and commit. Repeat for the next. The tests keep the moved features from sliding back, and the remaining layer packages shrink until they disappear.

Where this does not apply

A tiny application with one feature does not need sub-packages. Libraries with a technical focus (parsers, clients) are naturally organized by technical role. The reference is Spring Modulith's documentation on application modules, the Java language access rules define package-private access, and the discussion of layers and their costs explains the other side.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.